開発環境 |
Microsoft Visual Studio Community 2017 |
実行環境 |
Microsoft Windows 10 Home (64-bit) |
プロジェクトの種類 |
Visual C# / Windows フォーム アプリケーション (.NET Framework) |
プロジェクト名 |
bmp |
Form1.cs
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace bmp
{
public partial class Form1 : Form
{
private byte[] buf;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//var image = Image.FromFile(@"C:\tmp\pcg.bmp");
//var stream = new FileStream(@"C:\tmp\pcg.bmp", FileMode.Open);
uint biWidth = 256;
uint biHeight = 128;
uint biSizeImage = ((biWidth + 7) / 8) * biHeight;
uint bfOffBits = 14 + 40 + 8;
uint bfSize = bfOffBits + biSizeImage;
buf = new byte[bfSize];
// BITMAPFILEHEADER
WriteBuf2(0, 0x4d42); // "BM"
WriteBuf4(2, bfSize);
WriteBuf4(10, bfOffBits);
// BITMAPINFOHEADER
WriteBuf4(14, 40); // biSize
WriteBuf4(18, biWidth);
WriteBuf4(22, biHeight);
WriteBuf2(26, 1); // biPlanes
WriteBuf2(28, 1); // biBitCount
WriteBuf4(34, biSizeImage);
// RGBQUAD
WriteBuf4(54, 0x00000000);
WriteBuf4(58, 0x00ffffff);
var i = bfOffBits;
for(var y = 0; y < 128; y++)
{
for (var x = 0; x < 256; x += 8)
{
buf[i++] = (byte)y;
}
}
var stream = new MemoryStream(buf);
var image = Image.FromStream(stream);
pictureBox1.Width = (int)biWidth;
pictureBox1.Image = image;
}
private void WriteBuf2(int offset, ushort value)
{
var tmp = BitConverter.GetBytes(value);
Array.Copy(tmp, 0, buf, offset, 2);
}
private void WriteBuf4(int offset, uint value)
{
var tmp = BitConverter.GetBytes(value);
Array.Copy(tmp, 0, buf, offset, 4);
}
}
}

最終更新:2018年05月16日 16:38