将RGB8字节[]转换为位图 [英] Convert RGB8 byte[] to Bitmap

查看:287
本文介绍了将RGB8字节[]转换为位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有来自RGB8格式的相机的原始像素数据,需要将其转换为Bitmap.但是,Bitmap PixelFormat似乎仅支持RGB 16、24、32和48格式.

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.

我尝试使用PixelFormat.Format8bppIndexed,但是图像看起来变色并倒置.

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?

推荐答案

这会在您的图像中创建一个线性的8位灰度调色板.

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);

这篇关于将RGB8字节[]转换为位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆