从IntPtr创建位图

本文关键字:位图 创建 IntPtr | 更新日期: 2023-09-27 18:10:14

我正试图弄清楚如何使用USB视频摄像机API,这有点不太清楚(至少它似乎依赖于开发人员以前的知识,我不认为我理解"全图",双关语)。

我有以下成功接收数据的事件处理程序,目前我只能将其打印到控制台:

    void  _camera_OnPreviewBitmap(IntPtr pbyteBitmap, uint dwBufferSize,
                                  uint dwWidth, uint dwHeight,
                                  uint dwFrameNo, uint dwPreviewPixelFormat) {
        Console.WriteLine(string.Format("{0}, {1}, {2}, {3}, {4}, {5}", pbyteBitmap, dwBufferSize, dwWidth, dwHeight, dwFrameNo, dwPreviewPixelFormat));
        //The callback function gets the image data as “IntPtr” type. 
        //When using “System.Runtime.InteropServices.Marshal.Copy”, the image data can copy to the array. 
        //When using “System.Runtime.InteropServices.Marchal.ReadByte”, the image data can get thedirectory. 
        //Sometimes the process speed is fast when receiving the image data after the image data copy to the array with 
        //“System.Runtime.InteropServices.Marchal.Copy”. 
    } 

结果如下:

259129344, 1228800, 1280, 960, 195051, 1
250281984, 1228800, 1280, 960, 195052, 1
259129344, 1228800, 1280, 960, 195053, 1
250281984, 1228800, 1280, 960, 195054, 1
259129344, 1228800, 1280, 960, 195055, 1
250281984, 1228800, 1280, 960, 195056, 1
259129344, 1228800, 1280, 960, 195057, 1
250281984, 1228800, 1280, 960, 195058, 1
259129344, 1228800, 1280, 960, 195059, 1
250281984, 1228800, 1280, 960, 195060, 1
259129344, 1228800, 1280, 960, 195061, 1
250281984, 1228800, 1280, 960, 195062, 1

因此,这与图像尺寸(1280 x 960)是一致的,1228800是像素计数(缓冲区大小),像素格式的1意味着PIXEL_FORMAT_08_MONO_OR_RAW根据相机API像素格式enum(这也与这个BW相机一致)。

我的问题是:

我如何获取这些信息并使用它创建System.Drawing.Bitmap对象?

我已经尝试过了,没有成功(显然灰度图像实际上没有索引…):

        var bmp = new System.Drawing.Bitmap((int)dwWidth, (int)dwHeight, (int)dwBufferSize,
                                            PixelFormat.Format8bppIndexed, pbyteBitmap);

这最终会产生"Generic GDI+ error"

从IntPtr创建位图

您指定了一个索引格式,而没有给它一个调色板。

如果图像是灰度的,而不是直接使用指针,你可以用32bpp创建你的位图,锁定位,然后将RGB字节值设置为像素字节数据,这里是一个例子(使用不安全的代码为方便和速度):

Bitmap bmp = new Bitmap(1280, 960, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
var data = bmp.LockBits(new Rectangle(0, 0, 1280, 960), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
byte* srcBmpData = (byte*)pbyteBitmap.ToPointer();
byte* dstBmpData = (byte*)data.Scan0.ToPointer();
for (int buc = 0; buc < 1280 * 960; buc++)
{
    int currentDestPos = buc * 4;
    dstBmpData[currentDestPos] = dstBmpData[currentDestPos + 1] = dstBmpData[currentDestPos + 2] = srcBmpData[buc];
}
bmp.UnlockBits(data);