Convert RGB8 bytes [] to Bitmap

I have raw pixel data coming from the camera in RGB8 format that I need to convert to Bitmap . However, Bitmap PixelFormat only supports RGB 16, 24, 32, and 48.

I tried using PixelFormat.Format8bppIndexed , but the image looks discolored and inverted.

 public static Bitmap CopyDataToBitmap(byte[] data) { var bmp = new Bitmap(640, 480, PixelFormat.Format8bppIndexed); var bmpData = bmp.LockBits( new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat); Marshal.Copy(data, 0, bmpData.Scan0, data.Length); bmp.UnlockBits(bmpData); return bmp; } 

Is there any other way to correctly convert this data type?

+5
source share
1 answer

This creates a linear 8-bit grayscale palette in your image.

 bmp.UnlockBits(bmpData); var pal = bmp.Palette; for (int i = 0; i < 256; i++) pal.Entries[i] = Color.FromArgb(i, i, i); bmp.Palette = pal; return bmp; 

You still have to invert the scan lines, perhaps like this:

 for (int y = 0; y < bmp.Height; y++) Marshal.Copy(data, y * bmp.Width, bmpData.Scan0 + ((bmp.Height - 1 - y) * bmpData.Stride), bmpData.Stride); 
+2
source

Source: https://habr.com/ru/post/1203866/


All Articles