Save 32 bit bitmap as 1 bit .bmp file in C #

What is the easiest way to convert and save a 32-bit bitmap to a 1-bit (black and white) .bmp file in C #?

+4
source share
2 answers

This code will do its job:

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); byte[] scan = new byte[(w + 7) / 8]; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (x % 8 == 0) scan[x / 8] = 0; Color c = img.GetPixel(x, y); if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8)); } Marshal.Copy(scan, 0, (IntPtr)((long)data.Scan0 + data.Stride * y), scan.Length); } bmp.UnlockBits(data); return bmp; } 

You can speed it up if necessary by using insecure code to replace the GetPixel () method.

+8
source

easiest way to do this using clone ()

 using System.Drawing.Imaging; var original = //your source image; var rectangle = new Rectangle(0, 0, original.Width, original.Height); var bmp1bpp = original.Clone(rectangle, PixelFormat.Format1bppIndexed); 

How can this be denied, perhaps not the fastest way to do it, there is a much faster way to do it

+8
source

Source: https://habr.com/ru/post/1305966/


All Articles