更新PictureBox时可能导致ArgumentException的原因是什么?

时间:2012-04-04 16:15:02

标签: c# picturebox aforge argumentexception

决定尝试使用AForge视频和影像功能后,我尝试实施this simple demo

private void Main_Load(object sender, EventArgs e)
{
        // enumerate video devices
        FilterInfoCollection videoDevices = new FilterInfoCollection(
                        FilterCategory.VideoInputDevice);
        // create video source
        VideoCaptureDevice videoSource = new VideoCaptureDevice(
                        videoDevices[0].MonikerString);
        // set NewFrame event handler
        videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
        // start the video source
        videoSource.Start();
}

private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
        this.pictureBox1.Image = eventArgs.Frame;
}

问题在于我总是得到一个ArgumentException,但并不总是立即发生。它会弹出Application.Run(new Main());,但堆栈跟踪的顶部如下所示:

  • 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)

不确定这是否相关,但异常的ParamName属性为null。我试过在try ... catch块中包装图像赋值,但这没有帮助。我还检查过以确保图像在分配之前不为空。我还检查了非空,但是0x0大小的图像。

我做错了什么?有人可以建议解决方法吗?

1 个答案:

答案 0 :(得分:5)

我认为问题在于你不复制 在事件处理程序中传递的位图(帧)。

AForge文件说:

  

由于视频源可能有多个客户端,因此每个客户端都有责任   用于复制(克隆)传递的视频帧,因为视频源   在通知客户后处理自己的原始副本。

因此,如果您直接将框架分配给图片框 PictureBox时,AForge框架可以处理位图 正在尝试绘制位图。