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

本文介绍如何使用AForge库实现USB摄像头拍照功能,并提供了一个简单的WPF应用程序示例。包括无预览拍照和显示摄像头画面的同时进行图像抓拍两种场景。

项目中用到 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"

添加 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();
        }
    }
}

最终结果如下:

结果

<think>我们正在讨论AForge类库的下载方法。根据之前的对话历史和引用内容,用户已经明确询问下载方法,而之前的回答中已经提供了官方下载地址、GitHub仓库等信息。现在用户再次询问下载方法,可能是希望得到更简洁直接的步骤。根据引用内容,我们有以下相关信息:-引用[1]和[3]提供了两个示例项目的下载地址,但用户需要的是AForge类库本身的下载。-引用[2]提到了一个优快云博客链接,其中可能包含AForge类库的相关链接(但具体链接未给出)。-引用[4]展示了一段使用AForge操作摄像头的C#代码,但没有提供下载信息。回顾之前的回答,我们已经提供了:1.官方网站:http://www.aforgenet.com/2.直接下载页面:http://www.aforgenet.com/framework/downloads.html3.GitHub仓库:https://github.com/andrewkirillov/AForge.NET因此,这次回答应该重点强调这些官方下载渠道,给出清晰的步骤。另外,根据引用[2]中提到的优快云博客(https://blog.youkuaiyun.com/m_buddy/article/details/62417912),该博客可能也提供了下载链接或使用说明,但考虑到官方渠道更可靠,我们优先推荐官方下载。所以,回答可以这样组织:1.推荐官方网站下载(提供直接链接)2.推荐GitHub仓库下载(提供Releases链接)3.提示也可以通过NuGet安装(如果用户使用VisualStudio,这是最方便的方式)注意:用户可能混淆了AForge类库本身和示例项目,因此需要明确区分。最后,根据用户要求,生成相关问题。</think>### AForge类库下载方法 #### 1. **官方下载渠道** - **官方网站**:访问 [AForge.NET 框架下载页面](http://www.aforgenet.com/framework/downloads.html) - 直接下载包含完整源代码、二进制文件和文档的安装包 - 支持最新稳定版和历史版本下载 - **GitHub 发布页**:访问 [AForge.NET Releases](https://github.com/andrewkirillov/AForge.NET/releases) - 下载预编译的二进制文件(.dll)或完整源码压缩包(.zip) #### 2. **NuGet 安装(推荐)** 在 Visual Studio 中通过包管理器直接安装: ```bash Install-Package AForge -Version 2.2.5 # 核心库 Install-Package AForge.Video -Version 2.2.5 # 视频处理模块 Install-Package AForge.Imaging -Version 2.2.5 # 图像处理模块 ``` #### 3. **示例项目参考** - **视频播放示例**:[GitCode 项目](https://gitcode.com/open-source-toolkit/c3b07)[^1] - **拍照/录像实现**:[GitCode 项目](https://gitcode.com/Open-source-documentation-tutorial/d5cd7)[^3] - **摄像头操作代码**:[优快云 博客参考](https://blog.youkuaiyun.com/m_buddy/article/details/62417912)[^2][^4] > ⚠️ **注意事项** > 1. AForge 是**完全免费**的开源项目(MIT 许可证),无需付费 > 2. 下载后需添加引用:`AForge.dll`, `AForge.Video.dll`, `AForge.Imaging.dll` > 3. 建议使用 .NET Framework 4.0+ 环境 #### 4. **验证下载完整性** 通过 SHA256 校验文件: ```csharp using System.Security.Cryptography; var hash = SHA256.Create().ComputeHash(File.ReadAllBytes("AForge.dll")); var hexHash = BitConverter.ToString(hash).Replace("-", ""); ```
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值