Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

raw pixel array to gray scale BitmapImage

Tags:

c#

bitmap

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.

like image 911
chans Avatar asked Mar 17 '23 17:03

chans


2 Answers

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;
like image 75
TaW Avatar answered Mar 24 '23 22:03

TaW


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.

like image 21
bokibeg Avatar answered Mar 24 '23 20:03

bokibeg