我正在尝试使用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 :(得分: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);
}
}