如何在C#中使用GDI的圖像創建每像素1位的遮罩?我想從中創建掩碼的圖像保存在System.Drawing.Graphics對象中。從圖像創建1bpp遮罩
我已經看到在循環中使用Get/SetPixel的例子,這些例子太慢了。我感興趣的方法是僅使用BitBlits的方法,如this。我只是無法讓它在C#中工作,任何幫助都非常感謝。
如何在C#中使用GDI的圖像創建每像素1位的遮罩?我想從中創建掩碼的圖像保存在System.Drawing.Graphics對象中。從圖像創建1bpp遮罩
我已經看到在循環中使用Get/SetPixel的例子,這些例子太慢了。我感興趣的方法是僅使用BitBlits的方法,如this。我只是無法讓它在C#中工作,任何幫助都非常感謝。
試試這個:
using System.Drawing;
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);
for (int y = 0; y < h; y++) {
byte[] scan = new byte[(w + 7)/8];
for (int x = 0; x < w; x++) {
Color c = img.GetPixel(x, y);
if (c.GetBrightness() >= 0.5) scan[x/8] |= (byte)(0x80 >> (x % 8));
}
Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length);
}
bmp.UnlockBits(data);
return bmp;
}
GetPixel()是緩慢的,你可以用一個不安全的字節加快步伐*。
在Win32 C API中,創建單聲道蒙板的過程很簡單。
對於獎勵分數,通常需要將面罩抹回源位圖(使用SRC_AND)以將面罩顏色歸零。
謝謝你nobugz!我已經編輯了原始問題,因爲我試圖避免Get/SetPixel循環。我很抱歉。 – 2008-11-09 13:57:03