code_junkie

C#/GDI - Create 1bpp mask from image

Nov 12th, 2011
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. using System.Drawing;
  2. using System.Drawing.Imaging;
  3. using System.Runtime.InteropServices;
  4.  
  5. public static Bitmap BitmapTo1Bpp(Bitmap img) {
  6. int w = img.Width;
  7. int h = img.Height;
  8. Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);
  9. BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
  10. for (int y = 0; y < h; y++) {
  11. byte[] scan = new byte[(w + 7) / 8];
  12. for (int x = 0; x < w; x++) {
  13. Color c = img.GetPixel(x, y);
  14. if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));
  15. }
  16. Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length);
  17. }
  18. bmp.UnlockBits(data);
  19. return bmp;
  20. }
Add Comment
Please, Sign In to add comment