ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C#调用摄像头实现拍照功能

2020-09-19 22:50:41  阅读:205  来源: 互联网

标签:拍照 return C# videoSource dll AForge static NewFrame 摄像头


前言
老师要求我们学生做一套拍照身份验证系统,经过长时间的学习,有了这篇文章,希望能帮到读者们。

正文
首先介绍本文的主角:AForge
创建一个C#项目,引用必备的几个DLL

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;

至此,便可以开始编写代码了。

首先遍历操作系统上的摄像头控件:

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;
            }

        }

找到控件后就可以初始化摄像头:

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

标签:拍照,return,C#,videoSource,dll,AForge,static,NewFrame,摄像头
来源: https://blog.51cto.com/14492553/2536158

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有