C# WPF使用AForge类库操作USB摄像头拍照并保存
项目中用到 USB 摄像头,需要根据情况进行图像抓拍,查了半天资料,比较多的是使用 WPFMediaKit 和 AForge 。
但是由于项目要求不显示 USB 摄像头拍摄的画面,最终确定使用 AForge 解决。
下面用一个测试程序记录一下。
一、无预览拍照
首先建立一个 WPF 项目,我的就叫 AForgeTest,你们随意就好:
然后在 NuGet 包管理器中安装 AForge 库:
我只安装了图中打勾的几个库,这个根据自己项目需要安装就好。
不过用 USB 摄像头拍照必须安装:
AForge.Video
AForge.Control
AForge.Video.DirectShow
这三个库文件。
不习惯使用 NuGet 也可以到 AForge 的 .NET lib 下载页面下载。
在 MainWindow.xaml 文件中添加两个按钮:
<Window x:Class="AForgeTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:AForgeTest" mc:Ignorable="d" Title="MainWindow" Height="300" Width="300" Closing="Window_Closing"> <StackPanel> <Button Name="btnCapture" Click="btnCapture_Click">拍照</Button> <Button Name="btnOpenCamera" Click="btnOpenCamera_Click">打开</Button> </StackPanel> </Window>
后台交互逻辑如下:
using System; using System.Windows; namespace AForgeTest { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void btnOpenCamera_Click(object sender, EventArgs e) { CameraHelper.UpdateCameraDevices(); if (CameraHelper.CameraDevices.Count > 0) { CameraHelper.SetCameraDevice(0); } } private void btnCapture_Click(object sender, EventArgs e) { CameraHelper.CaptureImage(@"E:\1"); } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { CameraHelper.CloseDevice(); } } }
CameraHelper 类代码如下:
using System; using AForge.Video.DirectShow; using AForge.Controls; using System.Windows; using System.IO; using System.Drawing; using System.Drawing.Imaging; namespace AForgeTest { public static class CameraHelper { private static FilterInfoCollection _cameraDevices; private static VideoCaptureDevice div = null; private static VideoSourcePlayer sourcePlayer = new VideoSourcePlayer(); private static bool _isDisplay = false; //指示_isDisplay设置为true后,是否设置了其他的sourcePlayer,若未设置则_isDisplay重设为false private static bool isSet = false; /// <summary> /// 获取或设置摄像头设备,无设备为null /// </summary> public static FilterInfoCollection CameraDevices { get { return _cameraDevices; } set { _cameraDevices = value; } } /// <summary> /// 指示是否显示摄像头视频画面 /// 默认false /// </summary> public static bool IsDisplay { get { return _isDisplay; } set { _isDisplay = value; } } /// <summary> /// 获取或设置VideoSourcePlayer控件, /// 只有当IsDisplay设置为true时,该属性才可以设置成功 /// </summary> public static VideoSourcePlayer SourcePlayer { get { return sourcePlayer; } set { if (_isDisplay) { sourcePlayer = value; isSet = true; } } } /// <summary> /// 更新摄像头设备信息 /// </summary> public static void UpdateCameraDevices() { _cameraDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); } /// <summary> /// 设置使用的摄像头设备 /// </summary> /// <param name="index">设备在CameraDevices中的索引</param> /// <returns><see cref="bool"/></returns> public static bool SetCameraDevice(int index) { if (!isSet) _isDisplay = false; //无设备,返回false if (_cameraDevices.Count <= 0 || index < 0) return false; if (index > _cameraDevices.Count - 1) return false; // 设定初始视频设备 div = new VideoCaptureDevice(_cameraDevices[index].MonikerString); sourcePlayer.VideoSource = div; div.Start(); sourcePlayer.Start(); return true; } /// <summary> /// 截取一帧图像并保存 /// </summary> /// <param name="filePath">图像保存路径</param> /// <param name="fileName">保存的图像文件名</param> public static void CaptureImage(string filePath, string fileName = null) { if (sourcePlayer.VideoSource == null) return; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } try { //sourcePlayer.Start(); Image bitmap = sourcePlayer.GetCurrentVideoFrame(); if(fileName == null) fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"); bitmap.Save(filePath + @"\" + fileName + "-cap.jpg", ImageFormat.Jpeg); bitmap.Dispose(); //sourcePlayer.Stop(); } catch (Exception e) { MessageBox.Show(e.Message.ToString()); } } /// <summary> /// 关闭摄像头设备 /// </summary> public static void CloseDevice() { if (div != null && div.IsRunning) { sourcePlayer.Stop(); div.SignalToStop(); div = null; _cameraDevices = null; } } } }
最终效果如下:
首先单击打开按钮,然后单击拍照按钮,就会在指定路径下生成一个 jpg 文件。
单击打开按钮之后需要等待 2s 以上才能点击拍照(需要等待连接到摄像头),否则会报出异常,如下图:
二、显示摄像头拍摄画面和截取的图片
首先添加 System.Windows.Forms 和 WindowsFormsIntegration 的引用。
然后在 MainWindows.xmal 文件中加命名空间:
xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration" xmlns:aforge ="clr-namespace:AForge.Controls;assembly=AForge.Controls"12
添加 VideoSourcePlayer 和 Image 控件:
<wfi:WindowsFormsHost Grid.Row="0"> <aforge:VideoSourcePlayer x:Name="player" Height="480" Width="640"/> </wfi:WindowsFormsHost>
<Image Grid.Row="0" Grid.Column="1" Name="imgCapture" Stretch="Fill" Height="480" Width="640"/>
这里有个小细节,注意对 VideoSourcePlayer 命名时,一定要使用 x:Name 不要省略 x: ,否则无法在后台代码中使用(不要问我是怎么知道的)。
对 CameraHelper.cs 中的 CaptureImage 函数做一点修改:
/// <summary> /// 截取一帧图像并保存 /// </summary> /// <param name="filePath">图像保存路径</param> /// <param name="fileName">保存的图像文件名</param> /// <returns>如果保存成功,则返回完整路径,否则为 null</returns> public static string CaptureImage(string filePath, string fileName = null) { if (sourcePlayer.VideoSource == null) return null; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } try { Image bitmap = sourcePlayer.GetCurrentVideoFrame(); if(fileName == null) fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"); string fullPath = Path.Combine(filePath, fileName + "-cap.jpg"); bitmap.Save(fullPath, ImageFormat.Jpeg); bitmap.Dispose(); return fullPath; } catch (Exception e) { MessageBox.Show(e.Message.ToString()); return null; } }
修改后台代码如下:
using System; using System.Windows; using System.Windows.Media.Imaging; namespace AForgeTest { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); CameraHelper.IsDisplay = true; CameraHelper.SourcePlayer = player; CameraHelper.UpdateCameraDevices(); } private void btnOpenCamera_Click(object sender, EventArgs e) { if (CameraHelper.CameraDevices.Count > 0) { CameraHelper.SetCameraDevice(0); } } private void btnCapture_Click(object sender, EventArgs e) { string fullPath = CameraHelper.CaptureImage(AppDomain.CurrentDomain.BaseDirectory + @"\Capture"); BitmapImage bit = new BitmapImage(); bit.BeginInit(); bit.UriSource = new Uri(fullPath); bit.EndInit(); imgCapture.Source = bit; } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { CameraHelper.CloseDevice(); } } }
最终结果如下:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。
相关文章
- 我们在使用C#做项目的时候,基本上都需要制作登录界面,那么今天我们就来一步步看看,如果简单的实现登录界面呢,本文给出2个例子,由简入难,希望大家能够喜欢。...2020-06-25
- 这篇文章主要介绍了C# 字段和属性的的相关资料,文中示例代码非常详细,供大家参考和学习,感兴趣的朋友可以了解下...2020-11-03
- 这篇文章主要介绍了C#中截取字符串的的基本方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-03
- 本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
- 这篇文章主要介绍了C#实现简单的Http请求的方法,以实例形式较为详细的分析了C#实现Http请求的具体方法,需要的朋友可以参考下...2020-06-25
- 本文主要介绍了C#中new的几种用法,具有很好的参考价值,下面跟着小编一起来看下吧...2020-06-25
使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)
这篇文章主要介绍了使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25- 这篇文章主要介绍了C#开发Windows窗体应用程序的简单操作步骤,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-12
- 这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
- 最近做一个小项目不可避免的需要前端脚本与后台进行交互。由于是在asp.net中实现,故问题演化成asp.net中jiavascript与后台c#如何进行交互。...2020-06-25
- 本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
- 轻松学习C#的基础入门,了解C#最基本的知识点,C#是一种简洁的,类型安全的一种完全面向对象的开发语言,是Microsoft专门基于.NET Framework平台开发的而量身定做的高级程序设计语言,需要的朋友可以参考下...2020-06-25
- 本文主要介绍了C#变量命名规则小结,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-09
- 这篇文章主要介绍了C#绘制曲线图的方法,以完整实例形式较为详细的分析了C#进行曲线绘制的具体步骤与相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
- 本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
- 这篇文章主要介绍了c#自带缓存使用方法,包括获取数据缓存、设置数据缓存、移除指定数据缓存等方法,需要的朋友可以参考下...2020-06-25
- 这篇文章主要介绍了c#中(&&,||)与(&,|)的区别详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
- 这篇文章主要用实例讲解C#递归算法的概念以及用法,文中代码非常详细,帮助大家更好的参考和学习,感兴趣的朋友可以了解下...2020-06-25
- 下面小编就为大家带来一篇C#学习笔记- 随机函数Random()的用法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
- 这篇文章主要介绍了C#中list用法,结合实例形式分析了C#中list排序、运算、转换等常见操作技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25