[英]Create 1bpp mask from image
如何在 C# 中使用 GDI 从图像创建每像素 1 位掩码? 我试图从中创建蒙版的图像保存在 System.Drawing.Graphics 对象中。
我见过在循环中使用 Get/SetPixel 的例子,它们太慢了。 我感兴趣的方法是只使用 BitBlits 的方法,就像这样。 我只是无法让它在 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 中,创建单声道掩码的过程很简单。
对于奖励积分,通常需要将掩码 blit 回源位图(使用 SRC_AND)以将那里的掩码颜色归零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.