Create 1bpp mask from image
How do you create 1 bit per pixel mask from an image using GDI in C #? The image I'm trying to create the mask is stored in the System.Drawing.Graphics object.
I have seen examples that use Get / SetPixel in a loop that are too slow. The method I'm interested in is one that only uses BitBlits, like this . I just can't seem to get it to work in C #, any help is greatly appreciated.
+1
source to share
3 answers
Try the following:
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.
+6
source to share
In the Win32 C API, the process of creating a mono mask is simple.
- Create an uninitialzied 1bpp bitmap the size of the original bitmap.
- Select it in DC.
- Select the source bitmap in DC.
- The SetBkColor in the target DC matches the mask color of the source bitmap.
- BitBlt source to destination using SRC_COPY.
For bonus points, it's usually advisable to rekindle the mask back to the original raster map (using SRC_AND) to zero out the mask color.
+3
source to share