标签:
原文:在WPF中使用AForge.net控制摄像头拍照利用AForge.net控制摄像头拍照最方便的方法就是利用PictureBox显示摄像头画面,但在WPF中不能直接使用PictureBox。必须通过<WindowsFormsHost></WindowsFormsHost>来提供交换功能。其解决方法如下:
1、按照常规方法新建一个WPF应用程序;
2、添加引用
WindowsFormsIntegration (与WinForm交互的支持)
System.Windows.Forms (WinForm控件支持)
AForge.Video和AForge.Video.DirectShow(拷贝AForge.Video.dll,AForge.Video.DirectShow.dll,摄像头操作的库)
3、在XAML中添加 xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"(用wf代替System.Windows.Forms,即可使用<wf:PictureBox/>添加PictureBox控件
4、在界面相应位置添加
<WindowsFormsHost Name="winForm">
<wf:PictureBox Name="myPicture"/>
</WindowsFormsHost>(至此,界面层的设置完成)
5、代码部分
首先在窗口加载时初始化摄像头
myPhoto = pictureHost.Child as System.Windows.Forms.PictureBox;
FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count <= 0)
{
System.Windows.MessageBox.Show("请连接摄像头");
return;
}
else
{
CloseCaptureDevice();
myCaptureDevice = new VideoCaptureDevice(videoDevices[0].MonikerString);//myCaptureDevice的类型为VideoCaptureDevice,
myCaptureDevice.NewFrame += new NewFrameEventHandler(myCaptureDevice_NewFrame);
myCaptureDevice.DesiredFrameSize = new System.Drawing.Size(436, 360);//436, 360
myCaptureDevice.DesiredFrameRate = 10;
myCaptureDevice.Start();
}
PictureBox myPhoto = pictureHost.Child as System.Windows.Forms.PictureBox;//获取界面中的myPicture控件
void myCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)//帧处理程序
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
myPhoto.Image = bitmap.Clone(
new RectangleF((bitmap.Size.Width - 295) / 2, (bitmap.Size.Height - 413) / 2, 295, 413), //显示图像的宽度为295像素,高度为413像素
System.Drawing.Imaging.PixelFormat.Format32bppRgb);
}
关闭摄像头,释放系统资源(在窗口推出时必须调用)
private void CloseCaptureDevice()
{
if (myCaptureDevice != null)
{
if (myCaptureDevice.IsRunning)
{
myCaptureDevice.SignalToStop();
}
myCaptureDevice = null;
}
}
至此,使用AForge.net操作摄像头基本完成。摄像头捕获的画面能在PictureBox中显示出来,如果要实现拍照只需使用myCaptureDevice.Stop()停止摄像头,保存PictureBox中的Image属性即可。
原来想直接使用WPF中的Image控件显示摄像头,但在帧处理程序中始终提示无法操作帧图像,提示:没有权限操作,另一进程拥有该对象(大概是这个意思)。在这个问题上我纠结了大概有10天,一直都没有找到解决的办法,还请高人指点,谢谢!!
标签:
原文地址:http://www.cnblogs.com/lonelyxmas/p/5007717.html