What is the easiest way to convert and save a 32-bit Bitmap to a 1-bit (black/white) .bmp file in C#?
Asked
Active
Viewed 1.9k times
2 Answers
25
The easiest way to do achieve this by using the 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);
As disclaim this will maybe not the fastest way to do this there are much faster way's to do this

WiiMaxx
- 5,322
- 8
- 51
- 89
-
1this is definitely the easier way – SED Jul 29 '16 at 18:50
-
this works well and fast but brightness cannot be tuned. this is why I prefer https://stackoverflow.com/a/2574798/2323103 and adjust the 0.5 coefficient to whatever value I want – Couitchy May 14 '23 at 14:08
14
This code will get the job done:
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 unsafe code to replace the GetPixel() method.

Hans Passant
- 922,412
- 146
- 1,693
- 2,536
-
1If you're already locking the bits you might as well Marshal.Copy all the data to a byte[] and do it all at once. That'll save you the getpixel and the repeated marshal.copy overhead. – Ron Warholic Apr 04 '10 at 15:00
-
It's not that simple, the ImageFormat of the source image matters. – Hans Passant Apr 04 '10 at 15:08
-
Ron, that wouldn't work if you have a non-minimal stride in the source image unless you have the same in the destination image. (Stride >= width * bytesPerPixel) – Danny Varod Apr 04 '10 at 15:10