■ サンプル
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace SampleForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (this.pictureBox1.Image != null)
{
this.pictureBox1.Image.Dispose();
}
Bitmap srcBitmap = new Bitmap(@"20161215052204.gif");
// 1bppイメージを作成する
Bitmap newBitmap = new Bitmap(srcBitmap.Width, srcBitmap.Height,
PixelFormat.Format1bppIndexed);
// Bitmapをロックする
BitmapData bitmapData = newBitmap.LockBits(
new Rectangle(0, 0, newBitmap.Width, newBitmap.Height),
ImageLockMode.WriteOnly, newBitmap.PixelFormat);
// 新しい画像のピクセルデータを作成する
byte[] pixels = new byte[bitmapData.Stride * bitmapData.Height];
// 作成したピクセルデータをコピーする
IntPtr pointer = bitmapData.Scan0;
Marshal.Copy(pixels, 0, pointer, pixels.Length);
unsafe
{
byte* pixelPointer = (byte*)pointer;
for (int y = 0; y < bitmapData.Height; y++)
{
for (int x = 0; x < bitmapData.Width; x++)
{
// 明るさが0.5以上の時は白くする
if (0.5f <= srcBitmap.GetPixel(x, y).GetBrightness())
{
//ピクセルデータの位置
int position = (x >> 3) + bitmapData.Stride * y;
// 白くする
pixelPointer[position] |= (byte)(0x80 >> (x & 0x7));
}
}
}
}
// ロックを解除する
newBitmap.UnlockBits(bitmapData);
this.pictureBox1.Image = newBitmap;
}
}
}