Convert RGB8 byte[] to Bitmap

守給你的承諾、 提交于 2020-01-11 08:39:44

问题


I have raw pixel data coming from a camera in RGB8 format which I need to convert to a Bitmap. However, the Bitmap PixelFormat only seems to support RGB 16, 24, 32, and 48 formats.

I attempted to use PixelFormat.Format8bppIndexed, but the image appears 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 convert this data type correctly?


回答1:


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 will still need to invert the scan lines, maybe 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);


来源:https://stackoverflow.com/questions/26161441/convert-rgb8-byte-to-bitmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!