Question

I am trying to save webcam image in directory using AForge.NET.

Here is my Code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    FilterInfoCollection webcam;
    VideoCaptureDevice cam;
    Bitmap bitmap;

    private void Form1_Load(object sender, EventArgs e)
    {    
        webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
        cam = new VideoCaptureDevice(webcam[0].MonikerString);
        cam.NewFrame += new NewFrameEventHandler(cam_NewFrame);
        cam.Start();   
    }

    void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
    {
        bitmap = (Bitmap)eventArgs.Frame.Clone();
        pictureBox1.Image = bitmap;
        pictureBox1.Image.Save("c:\\image\\image1.jpg");
    }

But i am getting this exception:

InvalidOperationException was unhandled Object is currently in use elsewhere. If you are using Graphic objects after the GetHdc method, call the RealseHdc method.

Thanks in advance.

Was it helpful?

Solution

Problem is this line:

pictureBox1.Image = bitmap;
pictureBox1.Image.Save("c:\\image\\image1.jpg");

You are trying to save image that is not yet properly loaded and also you are facing cross-threading.

The solution in this case is to not use multiple threads when drawing.

void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
    bitmap = (Bitmap)eventArgs.Frame.Clone();
    pictureBox1.Image = bitmap;

         try
         {
             this.Invoke((MethodInvoker)delegate
             {
                 //saves image on its thread

                 pictureBox1.Image.Save("c:\\image\\image1.jpg");

             });
         }
         catch (Exception ex)
         {
             MessageBox.Show(""+ex);
         }
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top