根据图像创建1ppp掩码

本文关键字:1ppp 掩码 创建 图像 | 更新日期: 2023-09-27 17:48:50

如何在C#中使用GDI从图像创建每像素1位的掩码?我试图创建遮罩的图像保存在系统中。绘画Graphics对象。

我看到过在循环中使用Get/SetPixel的例子,它们太慢了。我感兴趣的方法是只使用BitBlits的方法,就像这样。我只是无法让它在C#中工作,任何帮助都将不胜感激。

根据图像创建1ppp掩码

试试这个:

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()速度较慢,可以使用不安全的字节*来加快速度。

在Win32C API中,创建单声道掩码的过程很简单。

  • 创建一个与源位图一样大的未初始化的1ppp位图
  • 将其选择为DC
  • 将源位图选择到DC中
  • 在目标DC上设置BkColor以匹配源位图的掩码颜色
  • 使用SRC_COPY将源BitBl定位到目标上

为了获得加分,通常需要将掩码闪电式传输回源位图(使用SRC_AND),以使那里的掩码颜色为零。

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