2014-01-17 134 views
1

我正在嘗試使用AForge.NET將網絡攝像頭圖像保存在目錄中。將圖片框中的圖像保存到特定目錄

這裏是我的代碼:

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"); 
    } 

但我得到這個異常:提前

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

感謝。

+0

看看這個http://msmvps.com/blogs/peterritchie/archive/2008/01/28/quot-object-is-currently-in-use-elsewhere-quot-error.aspx – Marek

回答

1

問題是這一行:

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

您試圖保存尚未正確加載圖像,你也面臨跨線程。

這種情況下的解決方案是在繪圖時不使用多個線程。

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); 
     } 
} 
+0

完美工作。 。 。非常感謝你 :) – user2517610