I have an array of raw pixel data. I would like to convert it into 8bpp Bitmap.
public static Bitmap ByteToGrayBitmap(byte[] rawBytes, int width, int height)
{
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height),
ImageLockMode.WriteOnly, bitmap.PixelFormat);
Marshal.Copy(rawBytes, 0, bitmapData .Scan0, rawBytes.Length);
bitmap.UnlockBits(bitmapData);
return bitmap;
}
bitmap looks like a color image instead of grayscale.
You need a 8-bit grayscale palette in your image.
Add this before you return:
var pal = bmp.Palette;
for (int i = 0; i < 256; i++) pal.Entries[i] = Color.FromArgb(i, i, i);
bmp.Palette = pal;
return bmp;
Try adding this before you return the bitmap:
for (int c = 0; c < bitmap.Palette.Entries.Length; c++)
bitmap.Palette.Entries[c] = Color.FromArgb(c, c, c);
It will create a typical grayscale palette.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With