【问题标题】:how to convert a raw RGB data array to a bitmap in C#如何在 C# 中将原始 RGB 数据数组转换为位图
【发布时间】:2013-10-02 10:42:48
【问题描述】:

我正在尝试将原始 RGB24 数据数组转换为 C# 中的位图,但这样做时遇到了麻烦。

这是对应的代码:

using System.Runtime.InteropServices;

byte[] frame;
//... code
frame = new byte[1280 * 960]; 

// code to get the frame

System.Runtime.InteropServices.GCHandle pinnedArray =   
      GCHandle.Alloc(frame, GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();

Bitmap bmp = new Bitmap(width, height, 3 * width, 
        PixelFormat.Format24bppRgb, pointer);

MemoryStream JPEGStream = new MemoryStream ();
bmp.Save(filepath, System.Drawing.Imaging.ImageFormat.Bmp);**

我得到一个

“System.Drawing.dll 中出现“System.AccessViolationException”类型的未处理异常”

使用上面的代码。

但是如果我改变:

Bitmap bmp = new Bitmap(width, height, stride, 
      PixelFormat.Format24bppRgb, pointer);

Bitmap bmp = new Bitmap(width/3, height/3, stride, 
      PixelFormat.Format24bppRgb, pointer);

我没有崩溃并获得 3 张图像,覆盖了总面积的 1/3。我应该得到一张覆盖整个 1280 X 960 区域空间的单一图像。

【问题讨论】:

    标签: c# image-processing bitmap camera


    【解决方案1】:

    Format24bppRgb 表示一个像素占用 24 位(3 个字节),而不是您在示例中预先分配的 1。

    更改分配的字节数以考虑每像素位数(以字节为单位,如果使用不同的大小,请不要忘记填充):

    frame = new byte[1280 * 960 * 3]; // 24bpp = 3 bytes
    

    【讨论】:

    • 谢谢阿列克谢。我忽略了这一点。现在我的程序没有崩溃,但我得到了 3 张 426 X 320 的图像,覆盖了 1280 x 960 像素的 1/3,而其余的 2/3 是黑色的。这就是图像的外观:tinypic.com/r/538ltd/5 我想要其中 1 个覆盖 1280 X 960 区域空间的块。你有什么想法吗?
    【解决方案2】:

    你试过 width-1 和 height-1 吗?

    【讨论】:

      猜你喜欢
      • 2010-12-07
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 2022-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-21
      相关资源
      最近更新 更多