Home > Article > Backend Development > C# case of using AForge to implement camera recording function
This article mainly introduces the sample code for calling AForge in C# to implement camera recording. It is of great practical value. Friends who need it can refer to it
1: First download the library file>>
You can also go to the official website to find>>
Download the full code of this tutorial>>
The output of MP4 requires the use of ffmpeg-related files. The library I packaged has already been brought. , the libraries found on the official website can be found in this directory:
2: Add these references:
3: Two global variables:
//用来操作摄像头 private VideoCaptureDevice Camera = null; //用来把每一帧图像编码到视频文件 private VideoFileWriter VideoOutPut = new VideoFileWriter(); 开始代码: //获取摄像头列表 var devs = new FilterInfoCollection(FilterCategory.VideoInputDevice); //实例化设备控制类(我选了第1个) Camera = new VideoCaptureDevice(devs[0].MonikerString); //配置录像参数(宽,高,帧率,比特率等参数)VideoCapabilities这个属性会返回摄像头支持哪些配置,从这里面选一个赋值接即可,我选了第1个 Camera.VideoResolution = Camera.VideoCapabilities[0]; //设置回调,aforge会不断从这个回调推出图像数据 Camera.NewFrame += Camera_NewFrame; //打开摄像头 Camera.Start(); //打开录像文件(如果没有则创建,如果有也会清空),这里还有关于 VideoOutPut.Open("E:/VIDEO.MP4", Camera.VideoResolution.FrameSize.Width, Camera.VideoResolution.FrameSize.Height, Camera.VideoResolution.AverageFrameRate, VideoCodec.MPEG4, Camera.VideoResolution.BitCount); 给AForge输出图像数据的回调方法: //图像缓存 private Bitmap bmp = new Bitmap(1, 1); //摄像头输出回调 private void Camera_NewFrame(object sender, NewFrameEventArgs eventArgs) { //写到文件 VideoOutPut.WriteVideoFrame(eventArgs.Frame); lock (bmp) { //释放上一个缓存 bmp.Dispose(); //保存一份缓存 bmp = eventArgs.Frame.Clone() as Bitmap; } }
End code:
//停摄像头 Camera.Stop(); //关闭录像文件,如果忘了不关闭,将会得到一个损坏的文件,无法播放 VideoOutPut.Close();
4: Modify App.config, Some things compatible with net2.0:
##
<?xml version="1.0" encoding="utf-8"?> <configuration> <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/> </startup> <supportedRuntime version="v2.0.50727"/> </configuration>Otherwise it will be like this:
The above is the detailed content of C# case of using AForge to implement camera recording function. For more information, please follow other related articles on the PHP Chinese website!