繁体   English   中英

从图像创建 1bpp 蒙版

[英]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 中,创建单声道掩码的过程很简单。

  • 创建一个与源位图一样大的未初始化的 1bpp 位图。
  • 将其选入 DC。
  • 选择源位图转换成 DC。
  • 在目标 DC 上设置 BkColor 以匹配源位图的掩码颜色。
  • 使用 SRC_COPY 将源 BitBlt 到目标。

对于奖励积分,通常需要将掩码 blit 回源位图(使用 SRC_AND)以将那里的掩码颜色归零。

你是说 LockBits 吗? Bob Powell 在这里有一个 LockBits 的概述; 这应该提供对 RGB 值的访问,以执行您需要的操作。 您可能还想查看 ColorMatrix, 就像这样

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM