本文介紹了在 C# 中將 32 位位圖另存為 1 位 .bmp 文件的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
在 C# 中將 32 位位圖轉換和保存為 1 位(黑/白).bmp 文件的最簡單方法是什么?
What is the easiest way to convert and save a 32-bit Bitmap to a 1-bit (black/white) .bmp file in C#?
推薦答案
此代碼將完成工作:
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;
}
如有必要,您可以通過使用不安全代碼替換 GetPixel() 方法來加快速度.
You can speed it up, if necessary, by using unsafe code to replace the GetPixel() method.
這篇關于在 C# 中將 32 位位圖另存為 1 位 .bmp 文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!