栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C#调用摄像头实现拍照功能的示例代码

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#调用摄像头实现拍照功能的示例代码

前言

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

正文

首先介绍本文的主角: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

到此这篇关于C#调用摄像头实现拍照功能的示例代码的文章就介绍到这了,更多相关C#调用摄像头拍照内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/121804.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号