从IntPtr创建位图

时间:2014-06-25 21:31:06

标签: c# marshalling system.drawing interopservices

我正在试图弄清楚如何使用USB摄像头API,这有点不太清楚(至少它似乎依赖于开发人员以前的知识,而且我不认为我理解&# 34;整个画面",双关语。)

我有以下事件处理程序,它成功接收数据,我现在只能打印到控制台:

    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像素格式枚举(这也与此BW相机一致)。

我的问题是:

  

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

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

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

这最终会产生"通用GDI +错误"。

1 个答案:

答案 0 :(得分:2)

您正在指定索引格式而不为其指定调色板。

如果图像是灰度的,而不是直接使用指针,你可以创建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);