利用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();
VideoCaptureDevice myCaptureDevice = null;
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)//帧处理程序
{
PictureBox myPhoto = myPicture;
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;
}
}
/// <summary>
/// 截图 程序,没有实验,等待中……
/// </summary>
private void Button3_Click(object sender, EventArgs e)
{
flag = 0;
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
}
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
if (flag == 0)
{
string img = dirc + "/" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
bitmap.Save(img);
flag = 1;
}
}
转载自:点击打开链接