从图像创建1bpp蒙版

如何在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中,创建单声道掩码的过程很简单。

  • 创建一个与源位图一样大的未初始化的1bpp位图。
  • 将其选择为DC。
  • 选择源位图到DC。
  • 目标DC上的SetBkColor与源位图的掩码颜色匹配。
  • BitBlt源使用SRC_COPY到目标。

对于奖励积分,通常需要将掩模重新点回到源位图(使用SRC_AND)以将掩模颜色归零。

你的意思是LockBits? Bob Powell 在这里概述了LockBits; 这应该提供对RGB值的访问,以满足您的需要。 你可能也想看看ColorMatrix, 就像这样 。