前言
老师要求咱们学生作一套拍照身份验证系统,通过长时间的学习,有了这篇文章,但愿能帮到读者们。git
正文
首先介绍本文的主角:AForge
建立一个C#项目,引用必备的几个DLLide
AForge.dll AForge.Controls.dll AForge.Imaging.dll AForge.Math.dll AForge.Video.DirectShow.dll AForge.Video.dll
这些DLL读者们能够在文末下载我附带的Demon学习
引用必要的命名空间测试
using AForge.Controls; using AForge.Video; using AForge.Video.DirectShow;
至此,即可以开始编写代码了。操作系统
首先遍历操做系统上的摄像头控件:code
public static bool GetDevices() { try { //枚举全部视频输入设备 videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); if (videoDevices.Count != 0) { Console.WriteLine("已找到视频设备."); return true; } return false; } catch (Exception ex) { Console.WriteLine("error:没有找到视频设备!具体缘由:" + ex.Message); return false; } }
找到控件后就能够初始化摄像头:orm
private static void CameraConn() { videoSource = new VideoCaptureDevice(videoDevices[selectedDeviceIndex].MonikerString); vid.VideoSource = videoSource; vid.Start(); }
可是这里为止,都只是摄像拍摄,若是须要拍照,则须要经过eventArgs.Frame.Clone()截取视频中的某一帧图像
这里就须要经过事件来处理:视频
public static void GrabBitmap() { if (videoSource == null) { return; } videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame); //新建事件 } static void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs) { Bitmap bmp = (Bitmap)eventArgs.Frame.Clone(); //Clone摄像头中的一帧 bmp.Save(path, ImageFormat.Png); videoSource.NewFrame -= new NewFrameEventHandler(videoSource_NewFrame); //若是这里不写这个,一下子会不停的拍照, }
代码中的path变量就是图片保存的位置,读者们能够自行设置路径。我这里默认是用户桌面下的Temp.png文件事件
测试代码下载地址:https://gitee.com/GiveCVE/csharp_camera/raw/master/OpenCamera.zip图片