Save 8 bit uncompressed windows bitmap file (.BMP) in c# / .Net
It took me about 3 years to figure this out. In .Net when you save an 8 bit bitmap from software (PixelFormat.Format8bppIndexed) via Save() it is saved by default in a compressed format (as is allowed by the .bmp pseudo-standard).
Now some Machine Vision libraries can’t load compressed 8 bit bitmaps (poor old Cognex, bless) so I had to figure out how to get .Net to save the .bmp file in an uncompressed format.
The following code save the bitmap as 8bit compressed (if the bitmap’s format is PixelFormat.Format8bppIndexed)
bitmap.Save("it.bmp");
Now Microsoft has not documented this whole area very well, but it is quite easy, you have to manually specify an image encoder and set its ‘Compression’ parameters as in the following code:
// Make sure that the blighter will be saved // uncompressed. var enc = GetEncoderInfo("image/bmp"); var parms = new EncoderParameters(1); var parm = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionNone); parms.Param[0] = parm; // Save the bitmap. bitmap.Save("it.bmp", enc, parms);
Where GetEncoderInfo() is defined as:
private static ImageCodecInfo GetEncoderInfo(String mimeType) { int j; ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; }
Here we set the Encoder.Compression parameter to EncoderValue.CompressionNone and this should ensure that the bitmap is saved uncompressed.
See this post for details of how to save an 8 bit greyscale image to disk from a byte array.
Reference:
http://msdn.microsoft.com/en-us/library/ytz20d80(v=vs.110).aspx