如何在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