1

如何在 C# 中使用 GDI 从图像中创建每像素 1 位的掩码?我试图从中创建蒙版的图像保存在 System.Drawing.Graphics 对象中。

我见过在循环中使用 Get/SetPixel 的例子,它们太慢了。我感兴趣的方法是只使用 BitBlits,就像这样。我只是无法让它在 C# 中工作,非常感谢任何帮助。

4

3 回答 3

6

尝试这个:

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() 很慢,你可以用一个不安全的字节来加速它*。

于 2008-11-07T21:24:58.507 回答
3

In the Win32 C API the process to create a mono mask is simple.

  • Create an uninitialzied 1bpp bitmap as big as the source bitmap.
  • Select it into a DC.
  • Select the source bitmap into a DC.
  • SetBkColor on the destination DC to match the mask color of the source bitmap.
  • BitBlt the source onto the destination using SRC_COPY.

For bonus points its then usually desirable to blit the mask back onto the source bitmap (using SRC_AND) to zero out the mask color there.

于 2009-03-15T12:22:04.570 回答
2

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

于 2008-11-09T13:56:05.153 回答