【问题标题】:Convert RGB8 byte[] to Bitmap将 RGB8 字节 [] 转换为位图
【发布时间】:2014-10-02 13:01:31
【问题描述】:

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

我尝试使用PixelFormat.Format8bppIndexed,但图像出现变色和倒置。

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

还有其他方法可以正确转换这种数据类型吗?

【问题讨论】:

  • 有用的文章:thisthis
  • 好奇:什么类型/型号的相机产生这种格式?另外:this 来源说它是 8 位单色格式。
  • this source 的另一个引用:RGB 是自下而上的,第一行有索引 (lines-1
  • Format8bppIndexed 是适合您情况的正确格式。此外,您需要制作将像素值 0 映射到 RGB (0,0,0) ... 255 到 RGB (255, 255, 255) 的 ColorPalette。请参阅 Image.Palette 属性。
  • @TaW 这是一个 Vista Ey2 虹膜扫描仪。

标签: c# bitmap


【解决方案1】:

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

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;

您仍然需要反转扫描线,可能是这样:

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

【讨论】:

  • @Barry:请注意循环条件中的1-off校正!
猜你喜欢
  • 2012-07-05
  • 1970-01-01
  • 2010-09-26
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多