C#/ GDI - 创建从图像1bpp面具 [英] C#/GDI - Create 1bpp mask from image

查看:242
本文介绍了C#/ GDI - 创建从图像1bpp面具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建每像素面膜1位在C#中使用GDI图像?我试图创建一个System.Drawing.Graphics对象持有的面具的形象。

How do you create a 1 bit per pixel mask from an image using GDI in C#? The image I am trying to create the mask from is held in a System.Drawing.Graphics object.

我已经看到了使用GET /中的setPixel一个循环的例子,这太慢。我感兴趣的方法是一个只使用BitBlits,如这个。我只是无法得到它在C#中工作,任何帮助深表感谢。

I have seen examples that use Get/SetPixel in a loop, which are too slow. The method that interests me is one that uses only BitBlits, like this. I just can't get it to work in C#, any help is much appreciated.

推荐答案

试试这个:

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()是缓慢的,你可以用一个不安全的字节加快步伐*

GetPixel() is slow, you can speed it up with an unsafe byte*.

这篇关于C#/ GDI - 创建从图像1bpp面具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆