色情報のあるビットマップを、モノクロ(2値)ビットマップに変換して、ビットマップファイルを保存できる、SaveMonoBitmapメソッドを作成しました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
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メソッドはこの形で利用できます。
1 2 3 4 |
Bitmap bmpColor = new Bitmap("c:\test.bmp"); SaveMonoBitmap(bmpColor, "c:\mono.bmp"); |
コメント