准备

添加引用
http://download.csdn.net/download/u011463646/10021001

.NET 2.0以上 你给项目添加.NET引用 找到PresentationCore添加上就可以了.

设计界面

运行

【代码】

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing.Imaging;
using System.Text;
using System.Windows;
using System.Windows.Forms;//添加的
using System.IO;
using System.Windows.Media.Imaging;
using AForge;
using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using Size = System.Drawing.Size;namespace AforgeCameraOne
{public partial class Form1 : Form{private FilterInfoCollection videoDevices;private VideoCaptureDevice videoSource;public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){try{// 枚举所有视频输入设备videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);if (videoDevices.Count == 0)throw new ApplicationException();foreach (FilterInfo device in videoDevices){int i = 1;tscbxCameras.Items.Add(device.Name);textBoxC.AppendText("摄像头" + i + "初始化完毕..." + "\n");textBoxC.ScrollToCaret();i++;}tscbxCameras.SelectedIndex = 0;}catch (ApplicationException){tscbxCameras.Items.Add("No local capture devices");videoDevices = null;}}private void btnConnect_Click(object sender, EventArgs e){CameraConn();}//连接摄像头1private void CameraConn(){VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[tscbxCameras.SelectedIndex].MonikerString);videoSource.DesiredFrameSize = new System.Drawing.Size(320, 240);videoSource.DesiredFrameRate = 1;videoSourcePlayer.VideoSource = videoSource;videoSourcePlayer.Start();}private void btnClose_Click(object sender, EventArgs e){videoSourcePlayer.SignalToStop();videoSourcePlayer.WaitForStop();}//主窗体关闭private void Form1_FormClosing(object sender, FormClosingEventArgs e){btnClose_Click(null, null);}private void Photograph_Click(object sender, EventArgs e){try{if (videoSourcePlayer.IsRunning){//System.Windows.Media.ImagingBitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(videoSourcePlayer.GetCurrentVideoFrame().GetHbitmap(),IntPtr.Zero,Int32Rect.Empty,//System.Drawing.Imaging;BitmapSizeOptions.FromEmptyOptions());PngBitmapEncoder pE = new PngBitmapEncoder();pE.Frames.Add(BitmapFrame.Create(bitmapSource));string picName = GetImagePath() + "\\" + "xiaosy" + ".jpg";textBoxC.AppendText("保存路径:" + picName + "\n");textBoxC.ScrollToCaret();if (File.Exists(picName)){File.Delete(picName);}using (Stream stream = File.Create(picName)){pE.Save(stream);}}}catch (Exception ex){MessageBox.Show("摄像头异常:" + ex.Message);}}private string GetImagePath(){string personImgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)+ Path.DirectorySeparatorChar.ToString() + "PersonImg";if (!Directory.Exists(personImgPath)){Directory.CreateDirectory(personImgPath);}return personImgPath;}private void btnExit_Click(object sender, EventArgs e){//拍照完成后关摄像头并刷新,同时关窗体if (videoSourcePlayer != null && videoSourcePlayer.IsRunning){videoSourcePlayer.SignalToStop();videoSourcePlayer.WaitForStop();}this.Close();}}
}

优点

videoSourcePlayer框的大小能够完整显示图像,比AForge Video好多了。

进一步改善,添加连续拍照功能

实时保存图像:

连续拍照AforgeCameraOne代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing.Imaging;
using System.Text;
using System.Windows;
using System.Windows.Forms;//添加的
using System.IO;
using System.Windows.Media.Imaging;
using AForge;
using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.FFMPEG;
using Size = System.Drawing.Size;namespace AforgeCameraOne
{public partial class Form1 : Form{private delegate void MyDelegateUI();//多线程问题private FilterInfoCollection videoDevices;  //摄像头设备  private VideoCaptureDevice videoSource;     //视频的来源选择  private VideoSourcePlayer videoSourcePlayer;    //AForge控制控件  private VideoFileWriter videoWriter;     //写入到视频  private bool is_record_video = false;   //是否开始录像  private bool is_multiPhotograph = false; //是否连续拍照 System.Timers.Timer timer_count;int tick_num = 0;public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){try{// 枚举所有视频输入设备videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);if (videoDevices.Count == 0)throw new ApplicationException();foreach (FilterInfo device in videoDevices){int i = 1;tscbxCameras.Items.Add(device.Name);textBoxC.AppendText("摄像头" + i + "初始化完毕..." + "\n");textBoxC.ScrollToCaret();i++;}tscbxCameras.SelectedIndex = 0;}catch (ApplicationException){tscbxCameras.Items.Add("No local capture devices");videoDevices = null;}}private void btnConnect_Click(object sender, EventArgs e){CameraConn();}//连接摄像头1private void CameraConn(){VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[tscbxCameras.SelectedIndex].MonikerString);videoSource.DesiredFrameSize = new System.Drawing.Size(640, 480);//不起作用videoSource.DesiredFrameRate = 1;videoSourcePlayer.VideoSource = videoSource;videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);videoSourcePlayer.Start();}private void btnClose_Click(object sender, EventArgs e){videoSourcePlayer.SignalToStop();videoSourcePlayer.WaitForStop();}//主窗体关闭private void Form1_FormClosing(object sender, FormClosingEventArgs e){btnClose_Click(null, null);}//拍一次照片private void btnPhotograph_Click(object sender, EventArgs e){try{if (videoSourcePlayer.IsRunning){//System.Windows.Media.ImagingBitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(videoSourcePlayer.GetCurrentVideoFrame().GetHbitmap(),IntPtr.Zero,Int32Rect.Empty,//System.Drawing.Imaging;BitmapSizeOptions.FromEmptyOptions());PngBitmapEncoder pE = new PngBitmapEncoder();pE.Frames.Add(BitmapFrame.Create(bitmapSource));string picName = GetImagePath() + "\\" + DateTime.Now.ToString("yyyyMMdd HH-mm-ss") + ".jpg";textBoxC.AppendText("保存路径:" + picName + "\n");textBoxC.ScrollToCaret();if (File.Exists(picName)){File.Delete(picName);}using (Stream stream = File.Create(picName)){pE.Save(stream);}}}catch (Exception ex){MessageBox.Show("摄像头异常:" + ex.Message);}}//拍多次照片private void btnMultiPhotograph_Click(object sender, EventArgs e){try{if (videoSourcePlayer.IsRunning && btnMultiPhotograph.Text.Trim()=="连续拍照"){//抓到图保存到指定路径//System.Drawing.Bitmap bmp1 = null;//bmp1 = videoSourcePlayer.GetCurrentVideoFrame();is_multiPhotograph = true;btnMultiPhotograph.Text = "终止拍照";return;//这句重要}if (videoSourcePlayer.IsRunning && btnMultiPhotograph.Text.Trim() == "终止拍照"){is_multiPhotograph = false;btnMultiPhotograph.Text = "连续拍照";}}catch (Exception ex){MessageBox.Show("摄像头异常:" + ex.Message);}}void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs){if (is_multiPhotograph){System.Drawing.Bitmap bmp1 = (System.Drawing.Bitmap)eventArgs.Frame.Clone();string picName = GetImagePath() + "\\" + DateTime.Now.ToString("yyyyMMdd HH-mm-ss") + ".jpg";MyDelegateUI d = delegate{this.textBoxC.AppendText("保存路径:" + picName + "\n");textBoxC.ScrollToCaret();};this.textBoxC.Invoke(d);if (File.Exists(picName)){File.Delete(picName);}using (Stream stream = File.Create(picName)){bmp1.Save(stream, ImageFormat.Bmp);}}}//获得路径private string GetImagePath(){string personImgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)+ Path.DirectorySeparatorChar.ToString() + "PersonImg";if (!Directory.Exists(personImgPath)){Directory.CreateDirectory(personImgPath);}return personImgPath;}//退出按钮private void btnExit_Click(object sender, EventArgs e){//拍照完成后关摄像头并刷新,同时关窗体if (videoSourcePlayer != null && videoSourcePlayer.IsRunning){videoSourcePlayer.SignalToStop();videoSourcePlayer.WaitForStop();}this.Close();}}
}

终极完善,添加Video的录制功能

这次优化了界面初始化的按钮状态,以及随时录制视频的功能。并在Video上打印文字如时间等等。环境配置与AForge Video同。

出现问题:

拍照+录像代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing.Imaging;
using System.Text;
using System.Windows;
using System.Windows.Forms;//添加的
using System.IO;
using System.Windows.Media.Imaging;
using AForge;
using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.FFMPEG;
using Size = System.Drawing.Size;namespace AforgeCameraOne
{public partial class Form1 : Form{private delegate void MyDelegateUI();//多线程问题private FilterInfoCollection videoDevices;  //摄像头设备  private VideoCaptureDevice videoSource;     //视频的来源选择  private VideoSourcePlayer videoSourcePlayer;    //AForge控制控件  private VideoFileWriter videoWriter=null;     //写入到视频  private bool is_record_video = false;   //是否开始录像  private bool is_multiPhotograph = false; //是否连续拍照 System.Drawing.Bitmap bmp1 = null;System.Timers.Timer timer_count;int tick_num = 0;int hour = 0;int i = 1;           //统计摄像头个数int width = 640;    //录制视频的宽度int height = 480;   //录制视频的高度int fps = 20;        //正常速率,fps越大速率越快,相当于快进public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){//初始化按钮状态btnClose.Enabled = false;btnPhotograph.Enabled = false;btnMultiPhotograph.Enabled = false;btnStarVideo.Enabled = false;btnPuaseVideo.Enabled = false;btnStopVideo.Enabled = false;try{// 枚举所有视频输入设备videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);if (videoDevices.Count == 0)throw new ApplicationException();foreach (FilterInfo device in videoDevices){tscbxCameras.Items.Add(device.Name);textBoxC.AppendText("摄像头" + i + "初始化完毕..." + "\n");textBoxC.ScrollToCaret();i++;}tscbxCameras.SelectedIndex = 0;}catch (ApplicationException){tscbxCameras.Items.Add("No local capture devices");videoDevices = null;}//秒表timer_count = new System.Timers.Timer();   //实例化Timer类,设置间隔时间为1000毫秒;timer_count.Elapsed += new System.Timers.ElapsedEventHandler(tick_count);   //到达时间的时候执行事件;timer_count.AutoReset = true;   //设置是执行一次(false)还是一直执行(true);timer_count.Interval = 1000;}//计时器响应函数public void tick_count(object source, System.Timers.ElapsedEventArgs e){tick_num++;int temp = tick_num;int sec = temp % 60;int min = temp / 60;if (min % 60 == 0){hour = min / 60;min = 0;}else{min = min - hour * 60;}String tick = hour.ToString() + ":" + min.ToString() + ":" + sec.ToString();MyDelegateUI d = delegate{this.labelTime.Text = tick;};this.labelTime.Invoke(d);}private void btnConnect_Click(object sender, EventArgs e){CameraConn();//激活初始化按钮状态btnClose.Enabled = true;btnPhotograph.Enabled = true;btnMultiPhotograph.Enabled = true;btnStarVideo.Enabled = true;btnPuaseVideo.Enabled = true;btnStopVideo.Enabled = true;}//连接摄像头1private void CameraConn(){VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[tscbxCameras.SelectedIndex].MonikerString);videoSource.DesiredFrameSize = new System.Drawing.Size(640, 480);//不起作用videoSource.DesiredFrameRate = 1;videoSourcePlayer.VideoSource = videoSource;videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);videoSourcePlayer.Start();}private void btnClose_Click(object sender, EventArgs e){videoSourcePlayer.SignalToStop();videoSourcePlayer.WaitForStop();}//主窗体关闭private void Form1_FormClosing(object sender, FormClosingEventArgs e){btnClose_Click(null, null);}//拍一次照片private void btnPhotograph_Click(object sender, EventArgs e){try{if (videoSourcePlayer.IsRunning){//System.Windows.Media.ImagingBitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(videoSourcePlayer.GetCurrentVideoFrame().GetHbitmap(),IntPtr.Zero,Int32Rect.Empty,//System.Drawing.Imaging;BitmapSizeOptions.FromEmptyOptions());PngBitmapEncoder pE = new PngBitmapEncoder();pE.Frames.Add(BitmapFrame.Create(bitmapSource));string picName = GetImagePath() + "\\" + DateTime.Now.ToString("yyyyMMdd HH-mm-ss") + ".jpg";textBoxC.AppendText("保存路径:" + picName + "\n");textBoxC.ScrollToCaret();if (File.Exists(picName)){File.Delete(picName);}using (Stream stream = File.Create(picName)){pE.Save(stream);}}}catch (Exception ex){MessageBox.Show("摄像头异常:" + ex.Message);}}//拍多次照片private void btnMultiPhotograph_Click(object sender, EventArgs e){try{if (videoSourcePlayer.IsRunning && btnMultiPhotograph.Text.Trim()=="连续拍照"){//抓到图保存到指定路径//System.Drawing.Bitmap bmp1 = null;//bmp1 = videoSourcePlayer.GetCurrentVideoFrame();is_multiPhotograph = true;btnMultiPhotograph.Text = "终止拍照";return;//这句重要}if (videoSourcePlayer.IsRunning && btnMultiPhotograph.Text.Trim() == "终止拍照"){is_multiPhotograph = false;btnMultiPhotograph.Text = "连续拍照";}}catch (Exception ex){MessageBox.Show("摄像头异常:" + ex.Message);}}void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs){bmp1 = (System.Drawing.Bitmap)eventArgs.Frame.Clone();//Write Imagesif (is_multiPhotograph){string picName = GetImagePath() + "\\" + DateTime.Now.ToString("yyyyMMdd HH-mm-ss-ffff") + ".jpg";MyDelegateUI d = delegate{this.textBoxC.AppendText("保存路径:" + picName + "\n");textBoxC.ScrollToCaret();};this.textBoxC.Invoke(d);if (File.Exists(picName)){File.Delete(picName);}using (Stream stream = File.Create(picName)){bmp1.Save(stream, ImageFormat.Bmp);}}//Write Videosif (is_record_video){bmp1 = videoSourcePlayer.GetCurrentVideoFrame();videoWriter.WriteVideoFrame(bmp1);}}//获得Images路径private string GetImagePath(){string personImgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)+ Path.DirectorySeparatorChar.ToString() + "PersonImg";if (!Directory.Exists(personImgPath)){Directory.CreateDirectory(personImgPath);}return personImgPath;}//获取Video相对路径private String GetVideoPath(){String personImgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)+ Path.DirectorySeparatorChar.ToString() + "MyVideo";if (!Directory.Exists(personImgPath)){Directory.CreateDirectory(personImgPath);}return personImgPath;}//退出按钮private void btnExit_Click(object sender, EventArgs e){if (this.videoWriter == null){//MessageBox.Show("videoWriter对象未实例化。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);//return;videoWriter = new VideoFileWriter();}if (this.videoWriter.IsOpen){MessageBox.Show("视频流还没有写完,请点击结束录制。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);return;}//拍照完成后关摄像头并刷新,同时关窗体if (videoSourcePlayer != null && videoSourcePlayer.IsRunning){videoSourcePlayer.SignalToStop();videoSourcePlayer.WaitForStop();}this.Close();}//开始录像private void btnStarVideo_Click(object sender, EventArgs e){try{//创建一个视频文件String picName = GetVideoPath() + "\\" + DateTime.Now.ToString("yyyyMMdd HH-mm-ss") + ".avi";textBoxC.AppendText("Video保存地址:" + picName + "\n");textBoxC.ScrollToCaret();timer_count.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;textBoxC.AppendText("录制中...\n");is_record_video = true;videoWriter = new VideoFileWriter();if (videoSourcePlayer.IsRunning){videoWriter.Open(picName, width, height, fps, VideoCodec.MPEG4);}else{MessageBox.Show("没有视频源输入,无法录制视频。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);}}catch (Exception ex){MessageBox.Show("摄像头异常:" + ex.Message);}}//暂停录像private void btnPuaseVideo_Click(object sender, EventArgs e){if (this.btnPuaseVideo.Text.Trim() == "暂停录像"){is_record_video = false;this.btnPuaseVideo.Text = "恢复录像";timer_count.Enabled = false;    //暂停计时return;}if (this.btnPuaseVideo.Text.Trim() == "恢复录像"){is_record_video = true;this.btnPuaseVideo.Text = "暂停录像";timer_count.Enabled = true;     //恢复计时}}private void btnStopVideo_Click(object sender, EventArgs e){this.is_record_video = false;this.videoWriter.Close();this.timer_count.Enabled = false;tick_num = 0;textBoxC.AppendText("录制停止!\n");textBoxC.ScrollToCaret();}}
}

参考

【1】C#操作摄像头 实现拍照功能 - 迷失的醉猫 - 博客园
http://www.cnblogs.com/xsyblogs/p/3551986.html
【2】C# 调用AForge类库操作摄像头 - CSDN博客
http://blog.csdn.net/chenhongwu666/article/details/40594365

C#操作Aforge摄像头 实现拍照、录像功能相关推荐

  1. android 前摄屏幕补光,异形显示屏及其前置摄像头的拍照补光方法与流程

    本申请涉及显示领域,特别是涉及一种异形显示屏及其前置摄像头的拍照补光方法. 背景技术: 随着全面屏显示技术的迅速发展,由于前置摄像头的存在,越来越多的屏幕采取了挖孔或是开口的设计,即在屏幕的一部分会包 ...

  2. Python+opencv调用摄像头实现拍照并保存

    Python+opencv调用摄像头实现拍照并保存 安装 OpenCV库 详细源码 注意事项 安装 OpenCV库 pip install opencv-python 详细源码 调用外接摄像头实现拍照 ...

  3. mfc调取摄像头显示并截图_利用MFC来显示摄像头并拍照

    今天是第一次尝试写一个MFC程序.水了一天,终于写好了.总结一下. 一.配置环境 调用摄像头是通过opencv库进行的,所以首先要配置好opencv 的环境.这个可以通过这个链接进行配置. https ...

  4. python操作window10摄像头

    工具库 python3.6 opencv-python pip install opencv-python import cv2 cap = cv2.VideoCapture(0) #打开摄像头cap ...

  5. 11-20210225华为海思Hi3518EV300在鸿蒙系统下测试摄像头(拍照+录像)

    11-20210225华为海思Hi3518EV300在鸿蒙系统下测试摄像头(拍照+录像) 2021/2/25 9:37 将Hi3518EV300在鸿蒙系统下配置为UVC模式,原厂(华为海思/江苏润和) ...

  6. matlab用摄像头拍照,使用MATLAB调用摄像头并拍照—详细代码

    大家也可以加我的交流群,所有资料我会在群里分享出来哦:977947271 2020/5/30: 近日每天都有十几个很明显的小号加群,而且有的大号进群竟然打广告和卖不良物品,经我和群友讨论后,加群需要1 ...

  7. 【全志T113-S3_100ask】14-1 linux采集usb摄像头实现拍照(FFmpeg、fswebcam)

    [全志T113-S3_100ask]14-1 linux采集usb摄像头实现拍照 背景 (一)FFmpeg 1.简介: 2.交叉编译FFmpeg 3.测试 (二)fswebcam 1.背景 2.交叉编 ...

  8. 树莓派(四):使用摄像头实现拍照和远程监控功能

    配置好树莓派的基本环境之后,就可以使用树莓派的摄像头模块了,接下来我会教你一些关于树莓派摄像头的基本操作:摄像头拍照,并实现摄像头的远程监控. 配置摄像头 首先将树莓派与摄像头模块插好: 插法是将蓝色 ...

  9. 摄像头自建html直播,html5调用摄像头实现拍照

    html5调用摄像头实现拍照 拍照 var video=document.getElementById("video"); var context=canvas.getContex ...

最新文章

  1. spring boot + spring batch 读数据库文件写入文本文件读文本文件写入数据库
  2. VC++ CryptoAPI最基本编程
  3. 《Linux命令行与shell脚本编程大全 第3版》Shell脚本编程基础---43
  4. 如何将yolo的标注(annotations).txt 坐标转换成tensorflow-yolov3(YunYang1994)的.txt 标注坐标?
  5. 2021-04-10 【数据库导数】数字类型的列如果位数过长,变为科学计数法问题
  6. 三朵云 华为_云时代和5G将重构网络结构
  7. Python面向对象编程基础
  8. 50道编程小题目之【分解质因数】
  9. 测试需求分析第一部分
  10. scala学习手记2 - scala中的循环
  11. 海康威视 摄像头 RTMP 转 FLV
  12. 乾颐堂现任明教教主(2014年课程)TCPIP协议详解卷一 第一节课笔记
  13. CouchBase简单介绍
  14. html ur是什么意思_url是什么意思?
  15. ODM操作MongoDB
  16. iis服务器版本信息泄漏,IIS短文件和文件夹泄漏漏洞
  17. WindowsCMD配置代理
  18. Gremlin 基础知识
  19. 【云宏大讲坛】超融合,融合的不仅是基础架构
  20. linux安装软件apt或者编译安装说明

热门文章

  1. excel分类_Excel中如何创建分类柱形图?
  2. Latex基本篇章结构
  3. 千聊语音课程导出注意事项
  4. 添加USB wifi驱动到RK3568
  5. 钟丽缇胯也太宽了吧,抹胸裙都快撑破了, 张伦硕能hold住么
  6. matlab c2d options,c2d(matlab中c2d用法例子)
  7. Web攻防——各脚本语言特有漏洞之ASP
  8. 身高、体重、脚长三个数值足以判断一个人的性别?贝叶斯分类模型
  9. 6款电脑必备的常用软件(办公/高效/小白入门)
  10. Selenium笔记(一)selenium简介、安装