在图片控件中显示传输的 HBITMAP

Displaying a transferred HBITMAP in a picture control

我有一个相机,它有一个用 C# 开发的库和一个用 C++ 6 编写的客户端应用程序。我已经为 link 这两个系统创建了一个 C# COM 包装器,它工作得很好。

在 C# COM 包装器中,我有一个 System.Drawing.Bitmap 对象,其中包含来自相机的当前帧。

在 C# COM 包装器中,我有一个函数 public void GetFrameHandle(ref IntPtr hBitmap, [MarshalAs(UnmanagedType.SysInt)] ref int width, [MarshalAs(UnmanagedType.SysInt)] ref int height),它基本上将 HBITMAP 从帧位图中获取到 C++

这似乎有些效果,我可以在 C++ 中看到图像,但由于像素格式不正确,所有图像都是乱码。

如何从 C++ 中的 HBITMAP 确定像素格式,然后在图片控件中显示正确的图像?

我进行了大量调查,似乎我需要从传输的 HBITMAP 创建一个新的 BITMAP,然后从正确的像素格式创建一个新的 HBITMAP,然后使用它来填充图片控制.

我不太确定如何开始这个过程

C# COM 服务器:

    /// <summary>
    /// Called when an image has been grabbed and is ready to process
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void StreamGrabber_ImageGrabbed(object sender, ImageGrabbedEventArgs e)
    {

        // process the image
        try
        {
            // Acquire the image from the camera. Only show the latest image. The camera may acquire images faster than the images can be displayed.

            // Get the grab result.
            IGrabResult grabResult = e.GrabResult;

            // Check if the image can be displayed.
            if (grabResult.GrabSucceeded)
            {
                if (grabResult.IsValid)
                {
                    // create a new bitmap object for holding the image data from the camera
                    // the bits and things need to be able to be set according to the c++ program's requirements.
                    System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(grabResult.Width, grabResult.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
                    // Lock the bits of the bitmap.
                    System.Drawing.Imaging.BitmapData bmpData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
                    // Place the pointer to the buffer of the bitmap.
                    converter.OutputPixelFormat = PixelType.BGR8packed;
                    IntPtr ptrBmp = bmpData.Scan0;
                    converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult); //Exception handling TODO
                    bitmap.UnlockBits(bmpData);

                    // Assign a temporary variable to dispose the bitmap after assigning the new bitmap to the display control.
                    System.Drawing.Bitmap bitmapOld = this.currentFrame;
                    // Provide the display control with the new bitmap. This action automatically updates the display.
                    // this may require some mutex to ensure that only entire frames are retrieved
                    this.currentFrame = bitmap;

                    // if the client window is set, output bitmap to it.
                    if (m_clientWindow != null)
                        m_clientWindow.DrawImage(currentFrame, new System.Drawing.Point(0, 0));


                    if (bitmapOld != null)
                    {
                        // Dispose the bitmap.
                        bitmapOld.Dispose();
                    }

                    // notify that a frame is ready to obtain
                    BroadcastFrameEvent();
                }
            }
            else
            {
                BroadcastErrorEvent("StreamGrabber_ImageGrabbed", String.Format("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription));
            }
        }
        catch (Exception exception)
        {
            BroadcastErrorEvent("StreamGrabber_ImageGrabbed", exception.ToString());
        }
        finally
        {
            // Dispose the grab result if needed for returning it to the grab loop.
            e.DisposeGrabResultIfClone();
        }


    }


   public void GetFrameHandle(ref IntPtr hBitmap, [MarshalAs(UnmanagedType.SysInt)] ref int width, [MarshalAs(UnmanagedType.SysInt)] ref int height)
    {
        if (this.currentFrame != null)
        {
            // System.Drawing.Imaging.BitmapData bmpData = null;
            try
            {

                hBitmap = this.currentFrame.GetHbitmap();

                width = currentFrame.Width;
                height = currentFrame.Height;

            }
            catch (Exception ex)
            {
                BroadcastErrorEvent("GetFrame", ex.ToString());
            }
        }
    }


    public void SaveFrame(string filename)
    {
        try
        {
            if (m_debugMode == 1)
                MessageBox.Show("Filename = " + filename, "GigE COM Wrapper Debug");

            if (this.currentFrame != null)
                this.currentFrame.Save(filename, System.Drawing.Imaging.ImageFormat.Bmp);
        }
        catch (Exception ex)
        {
            BroadcastErrorEvent("SaveFrame", ex.ToString());
        }
    }

C++ 客户端:

    // When a frame is ready to process
    HRESULT CameraEventHandler::OnFrameReady()
    {
        HRESULT hr = S_OK;

        //  if (m_debug == 1)
        //      MessageBox(NULL, "Frame is ready", "COM event received", MB_OK);

        // grab the frame from the COM wrapper and display it


        long pOutHb;

        if (pCamera != NULL)
        {
            BSTR bsFilename = SysAllocString(L"frame.bmp");

            hr = pCamera->SaveFrame(bsFilename);
            if (!SUCCEEDED(hr))
            {
                MessageBox(NULL, "COM Error", "Fail", MB_OK);
                return hr;
            }

            hr = pCamera->GetFrameHandle(&pOutHb, &width, &height);

            if (SUCCEEDED(hr))
            {

                BITMAP bm;
                HBITMAP hbFrameFromCOM;

                hbFrameFromCOM = (HBITMAP)pOutHb;

                // get the bitmap from the HBITMAP
                GetObject(hbFrameFromCOM, sizeof(BITMAP), &bm);

                LONG size = bm.bmWidthBytes * bm.bmHeight;

                        //create the bitmap?
                        // copy data across?
                        // create a new HBITMAP (hb)

                if (pDialog != NULL)
                {
                    // post the message
                    // this signals the dialog to update the picture control with the HBITMAP

                    pDialog->SendMessage(WM_REFRESH_BITMAP);
                }
            }
            else
                if (m_debug == 1)
                    MessageBox(NULL, "Get bitmap handle failed", "Fail", MB_OK);

        }

        return hr;
    }

不确定如何进行。

有趣的是,我从 C# 代码中保存的 frame.bmp 也是乱码。我认为这两个问题是相关的,但我不能在这里加入点。

感谢您的帮助。

感谢您的帮助,我才能够让它正常工作。

上面的代码非常正确,除了像素格式需要在相机和用作内部帧缓冲区的位图之间的 C# COM 包装器中匹配。

帧稳定后输出的灰度图像是因为我在c++客户端中将相机模式设置为灰度引起的。我改成了YUV,一切正常

可以设置模式的地方很多!

我不需要担心更改 C++ 客户端中的任何内容。只需要将COM wrapper 发送的HBITMAP 扔到对话框的图片控件上即可显示。

干杯。