C# WPF使用AForge类库操作USB摄像头拍照并保存

 更新时间:2022年03月27日 08:20:57   作者:晓风-杨柳  
这篇文章主要为大家详细介绍了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#实现将HTML转换成纯文本的方法

    C#实现将HTML转换成纯文本的方法

    这篇文章主要介绍了C#实现将HTML转换成纯文本的方法,基于自定义类实现文本转换功能,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07
  • C#使用iCSharpcode进行文件压缩实现方法

    C#使用iCSharpcode进行文件压缩实现方法

    这篇文章主要介绍了C#使用iCSharpcode进行文件压缩实现方法,末尾附有完整实例,有助于大家参考借鉴,需要的朋友可以参考下
    2014-08-08
  • C#使用TimeSpan时间计算的简单实现

    C#使用TimeSpan时间计算的简单实现

    这篇文章主要给大家介绍了关于C#使用TimeSpan时间计算的相关资料,以及通过一个实例代码给大家介绍了C#使用timespan和timer完成一个简单的倒计时器的方法,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧
    2018-06-06
  • c#版在pc端发起微信扫码支付的实例

    c#版在pc端发起微信扫码支付的实例

    本篇文章主要介绍了c#版在pc端发起微信扫码支付的实例,具有一定的参考价值,有兴趣的可以了解一下。
    2016-11-11
  • C#实现获取设置IP地址小工具

    C#实现获取设置IP地址小工具

    c# 开发,方便更改IP地址。由于公司和家里的ip设置不一样,公司要求手动设置,在家可以自动获取IP,切都是无线网络,为了方便操作,故做了这个小工具!
    2015-06-06
  • C# 并行和多线程编程——Task进阶知识

    C# 并行和多线程编程——Task进阶知识

    这篇文章主要介绍了C# 并行和多线程编程——Task进阶知识的的相关资料,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下
    2021-02-02
  • 基于C#实现FTP下载文件

    基于C#实现FTP下载文件

    这篇文章主要为大家详细介绍了如何利用C#实现FTP下载文件,文中的示例代码讲解详细,对我们学习C#有一定的帮助,感兴趣的小伙伴可以跟随小编一起了解一下
    2022-12-12
  • C# winform编程中响应回车键的实现代码

    C# winform编程中响应回车键的实现代码

    这篇文章主要介绍了C# winform编程中响应回车键的实现代码,既在窗口上响应回车键事件的方法,需要的朋友可以参考下
    2014-08-08
  • c#反射机制学习和利用反射获取类型信息

    c#反射机制学习和利用反射获取类型信息

    反射(Reflection)是.NET中的重要机制,通过放射,可以在运行时获得.NET中每一个类型(包括类、结构、委托、接口和枚举等)的成员,包括方法、属性、事件,以及构造函数等。还可以获得每个成员的名称、限定符和参数等。有了反射,即可对每一个类型了如指掌。如果获得了构造函数的信息,即可直接创建对象,即使这个对象的类型在编译时还不知道
    2014-01-01
  • C#将dll打包到程序中的具体实现

    C#将dll打包到程序中的具体实现

    这篇文章介绍了C#将dll打包到程序中的具体实现,有需要的朋友可以参考一下
    2013-10-10

最新评论