winforms 为什么获取异常参数是无效的,当试图加载一个位图图像到pictureBox?

krugob8w  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(117)

当我使用一个在行上有断点的调试程序时:

pictureBox1.Invoke(new Action(() => pictureBox1.Image = bitmap));

当它试图执行这一行时,它会抛出异常错误。当我把鼠标放在这一行的位图上时,我没有看到任何问题。
我试着改变pictureBox1的大小和大小模式,但它没有改变任何东西。
异常消息:

System.ArgumentException
  HResult=0x80070057
  Message=Parameter is not valid.
  Source=System.Drawing
  StackTrace:
   at System.Drawing.Image.get_Width()
   at System.Drawing.Image.get_Size()
   at System.Windows.Forms.PictureBox.ImageRectangleFromSizeMode(PictureBoxSizeMode mode)
   at System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe)
   at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
   at System.Windows.Forms.Control.WmPaint(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

方法:

private void DisplayFrameInPictureBox(Mat frame)
{
    // Create a copy of the Mat frame
    using (var frameCopy = new Mat())
    {
        frame.CopyTo(frameCopy);

        // Convert Mat copy to Bitmap
        using (var bitmap = frameCopy.ToBitmap())
        {
            // Display the bitmap in the PictureBox
            if (pictureBox1.InvokeRequired)
            {
                pictureBox1.Invoke(new Action(() => pictureBox1.Image = bitmap));
            }
            else
            {
                pictureBox1.Image = bitmap;
            }
        }
    }
}
7rfyedvj

7rfyedvj1#

尝试使用局部变量而不是using语句的主题:

using (var bitmap = frameCopy.ToBitmap())
{
    // Display the bitmap in the PictureBox
    if (pictureBox1.InvokeRequired)
    {
        var bmp = bitmap;

        pictureBox1.Invoke(new Action(() => pictureBox1.Image = bmp));
    }
    else
    {
        pictureBox1.Image = bitmap;
    }
}

相关问题