C# Save Grayscale byte array Image (byte[]) as Bitmap file (.bmp) example
Here is a quick, dirty and inefficient example of how to save an 8bit Grey scale image stored in a C# byte array as a 32bit bitmap file (.bmp). Saving bitmaps can be quite suprisingly difficult in .NET so I am posting this for future reference!
This code copies each byte (8 bit pixel) in the 8bit image into an array of 32bit pixels (4 bytes per pixel) and then saves it to disk. Note that you have to build your project with the ‘Allow unsafe code’ checkbox checked (go to project properties / Build and you will see the ‘Allow unsafe code’ checkbox.)
public void SaveAsBitmap(string fileName, int width, int height, byte[] imageData) { // Need to copy our 8 bit greyscale image into a 32bit layout. // Choosing 32bit rather than 24 bit as its easier to calculate stride etc. // This will be slow enough and isn't the most efficient method. var data = new byte[width * height * 4]; int o = 0; for (var i = 0; i < width * height; i++) { var value = imageData[i]; // Greyscale image so r, g, b, get the same // intensity value. data[o++] = value; data[o++] = value; data[o++] = value; data[o++] = 0; // Alpha isn't actually used } unsafe { fixed (byte* ptr = data) { // Create a bitmap wit a raw pointer to the data using (Bitmap image = new Bitmap(width, height, width * 4, PixelFormat.Format32bppRgb, new IntPtr(ptr))) { // And save it. image.Save(Path.ChangeExtension(fileName, ".bmp")); } } } }
Thanks to all on this thread for the pointers!
Update, 02/2014:
This code will save the 8 bit bitmap in a compressed (but perfectly valid) format, to have your software save it in an uncompressed format take a look at this post.