色情報のあるビットマップを、モノクロ(2値)ビットマップに変換して、ビットマップファイルを保存できる、SaveMonoBitmapメソッドを作成しました。
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
public static void SaveMonoBitmap(Bitmap bmpColor, string strSaveBitmapPath)
{
Bitmap bmpMono = Get1bppIndexedImage(bmpColor);
bmpMono.SetResolution(200, 200);
ImageCodecInfo imageCodecInfo;
imageCodecInfo = GetEncoderInfo("image/bmp");
EncoderParameters encoderParameters = new EncoderParameters(2);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 1L);
encoderParameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4);
bmpMono.Save(strSaveBitmapPath, imageCodecInfo, encoderParameters);
}
private static Bitmap Get1bppIndexedImage(Bitmap bmp)
{
Bitmap monoBmp = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format1bppIndexed);
BitmapData data = monoBmp.LockBits(
new Rectangle(0, 0, monoBmp.Width, monoBmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
if (bmp.GetPixel(x, y).GetBrightness() > 0.5)
SetIndexedPixel(x, y, data, true);
else
SetIndexedPixel(x, y, data, false);
}
}
monoBmp.UnlockBits(data);
return monoBmp;
}
private static unsafe void SetIndexedPixel(int x, int y, BitmapData bmd, bool pixel)
{
byte* p = (byte*)bmd.Scan0.ToPointer();
int index = y * bmd.Stride + (x >> 3);
byte mask = (byte)(0x80 >> (x & 0x7));
if (pixel)
p[index] |= mask;
else
p[index] &= (byte)(mask ^ 0xff);
}
private static ImageCodecInfo GetEncoderInfo(string mineType)
{
ImageCodecInfo[] encs = ImageCodecInfo.GetImageEncoders();
foreach (System.Drawing.Imaging.ImageCodecInfo enc in encs)
if (enc.MimeType == mineType)
return enc;
return null;
}
SaveMonoBitmapメソッドはこの形で利用できます。
Bitmap bmpColor = new Bitmap("c:\test.bmp");
SaveMonoBitmap(bmpColor, "c:\mono.bmp");
最近のコメント