从图像创建1bpp遮罩 [英] Create 1bpp mask from image
本文介绍了从图像创建1bpp遮罩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在C#中使用GDI的图像创建每像素1位掩码?我试图创建掩码的图像保存在System.Drawing.Graphics对象中。
我已经在循环中看到了使用Get / SetPixel的示例,它太慢了。我感兴趣的方法是仅使用BitBlits的方法,如 this 一>。我只是无法在C#中使用它,任何帮助都非常感谢。
解决方案试试这个:
using System.Drawing;
使用System.Drawing.Imaging;
使用System.Runtime.InteropServices;
...
public static Bitmap BitmapTo1Bpp(Bitmap img){
int w = img.Width;
int h = img.Height;
位图bmp =新位图(w,h,PixelFormat.Format1bppIndexed);
BitmapData data = bmp.LockBits(new Rectangle(0,0,w,h),ImageLockMode.ReadWrite,PixelFormat.Format1bppIndexed);
for(int y = 0; y byte [] scan = new byte [(w + 7)/ 8];
for(int x = 0; x Color c = img.GetPixel(x,y); (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()速度很慢,可以用不安全的字节加速* 。
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.
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.
解决方案
Try this:
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() is slow, you can speed it up with an unsafe byte*.
这篇关于从图像创建1bpp遮罩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文