保存32位的位图作为在C#1比特.bmp文件 [英] Save a 32-bit Bitmap as 1-bit .bmp file in C#
本文介绍了保存32位的位图作为在C#1比特.bmp文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是转换和一个32位的位图保存到1位(黑/白).bmp文件在C#中最简单的方法?
What is the easiest way to convert and save a 32-bit Bitmap to a 1-bit (black/white) .bmp file in C#?
推荐答案
这code将完成这项工作:
This code will get the job done:
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
...
public static Bitmap BitmapTo1Bpp(Bitmap img) {
int w = img.Width;
int h = img.Height;
Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);
BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
byte[] scan = new byte[(w + 7) / 8];
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
if (x % 8 == 0) scan[x / 8] = 0;
Color c = img.GetPixel(x, y);
if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));
}
Marshal.Copy(scan, 0, (IntPtr)((long)data.Scan0 + data.Stride * y), scan.Length);
}
bmp.UnlockBits(data);
return bmp;
}
您可以加快步伐,如果有必要,通过使用不安全code来代替getPixel()方法。
You can speed it up, if necessary, by using unsafe code to replace the GetPixel() method.
这篇关于保存32位的位图作为在C#1比特.bmp文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文