Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What might cause an ArgumentException when updating a PictureBox?

Having decided to try AForge for video and imaging stuff, I tried to implement 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;
}

The problem is that I always get an ArgumentException, though doesn't always happen right away. It pops up on Application.Run(new Main());, but the top of the stacktrace looks like this:

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

Not sure if this is relevant, but the ParamName attribute of the exception is null. I've tried wrapping the image assignment in a try...catch block, but this didn't help. I've also checked to make sure that the image is not null before assignment. I've also checked for non-null, but 0x0 sized images.

What have I done wrong? Can anyone suggest a workaround?

like image 873
Tom Wright Avatar asked Apr 04 '12 16:04

Tom Wright


People also ask

What are the different image formats that a PictureBox control can display?

The Windows Forms PictureBox control is used to display graphics in bitmap, GIF, JPEG, metafile, or icon format.

What is the use of PictureBox?

Typically the PictureBox is used to display graphics from a bitmap, metafile, icon, JPEG, GIF, or PNG file. Set the Image property to the Image you want to display, either at design time or at run time.

How do you move an image in a PictureBox?

To move the image, click the move button, click on the image, keep hold the clicked mouse button and drag.


1 Answers

I think the problem is that you do not make a copy of the passed bitmap (frame) in your event handler.

The AForge documentation says:

Since video source may have multiple clients, each client is responsible for making a copy (cloning) of the passed video frame, because the video source disposes its own original copy after notifying of clients.

So, if you directly assign the frame to the picture box the bitmap could be disposed by the AForge framework while the PictureBox is trying to draw the bitmap.

like image 108
Hans Avatar answered Oct 05 '22 22:10

Hans