문제

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.

도움이 되었습니까?

해결책

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);
         }
 }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top