WPF连接USB相机,拍照,视频 示例

USB相机连接

项目通过AForge库实现WPF 连接相机,进行拍照录像。

安装 AForge 库

在NuGet 中下载安装这三个包

AForge.Video

AForge.Control

AForge.Video.DirectShow

代码示例

辅助类 CameraHelper.cs

cs 复制代码
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows;
using AForge.Controls;
using AForge.Video.DirectShow;

namespace WpfApp4
{
    public static class CameraHelper
    {
        private static FilterInfoCollection _cameraDevices;
        private static VideoCaptureDevice div = null;
        private static VideoSourcePlayer sourcePlayer = new VideoSourcePlayer();
        public static bool _isDisplay = false;
        // 指示_isDisplay设置为true后,是否设置了其他的sourcePlayer,若未设置则_isDispaly重设为false
        private static bool isSet = false;

        /// <summary>
        /// 获取或设置摄像头设备,无设备则为null
        /// </summary>
        public static FilterInfoCollection CameraDevices
        {
            get
            {
                return _cameraDevices;
            }
            set
            {
                _cameraDevices = value;
            }
        }

        /// <summary>
        /// 指示是否显示摄像头画面
        /// </summary>
        public static bool IsDisplay
        {
            get { return _isDisplay; }
            set { _isDisplay = value; }
        }

        /// <summary>
        ///  获取或设置VideoSourcePlayer控件
        ///  只有当IsDispaly设置为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">设备在CameraDevice中的索引</param>
        /// <returns></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>
        /// <returns></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;
            }

        }

        /// <summary>
        /// 关闭相机 
        /// </summary>
        public static void CloseDevice()
        {
            if(div!= null && div.IsRunning)
            {
                sourcePlayer.Stop();
                div.SignalToStop();
                div = null;
                _cameraDevices = null;
            }
        }
    }
}

MainWindow.xaml

cs 复制代码
<Window x:Class="WpfApp3.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:WpfApp3"
        xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
        xmlns:aforge ="clr-namespace:AForge.Controls;assembly=AForge.Controls"
        
        Closing="Window_Closing"
        mc:Ignorable="d"
        Title="MainWindow" Height="600" Width="1280">
    <Grid>
        <StackPanel>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <wfi:WindowsFormsHost Grid.Column="0">
                    <aforge:VideoSourcePlayer x:Name="player" Height="480" Width="640"/>
                </wfi:WindowsFormsHost>

                <Image Grid.Column="1" Name="imgCapture" Stretch="Fill" Height="480" Width="640"/>
            </Grid>

            <Button Name="btnCapture" Click="btnCapture_Click">拍照</Button>
            <Button Name="btnOpenCamera" Click="btnOpenCamera_Click">打开</Button>
            <Button Name="btnCloseCamera" Click="btnCloseCamera_Click">关闭</Button>
        </StackPanel>
    </Grid>
</Window>

MainWindow.xaml.cs

cs 复制代码
using System;
using System.Windows;
using System.Windows.Media.Imaging;
using WpfApp4;

namespace WpfApp3
{
    /// <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, RoutedEventArgs e)
        {

            CameraHelper.UpdateCameraDevices();
            if (CameraHelper.CameraDevices.Count > 0)
            {
                CameraHelper.SetCameraDevice(0);
            }
        }

        private void btnCapture_Click(object sender, RoutedEventArgs 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();
        }

        private void btnCloseCamera_Click(object sender, RoutedEventArgs e)
        {
            CameraHelper.CloseDevice();
        }
    }
}

实现效果

左边是实时录像,右边是拍照定格,且照片可保存

相关推荐
唐梓航-求职中5 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
听麟7 小时前
HarmonyOS 6.0+ APP AR文旅导览系统开发实战:空间定位与文物交互落地
人工智能·深度学习·华为·ar·wpf·harmonyos
bugcome_com7 小时前
阿里云 OSS C# SDK 使用实践与参数详解
阿里云·c#
movigo7_dou7 小时前
工业相机镜头参数和选型
图像处理·数码相机
懒人咖17 小时前
缺料分析时携带用料清单的二开字段
c#·金蝶云星空
bugcome_com18 小时前
深入了解 C# 编程环境及其开发工具
c#
wfserial20 小时前
c#使用微软自带speech选择男声仍然是女声的一种原因
microsoft·c#·speech
阔皮大师21 小时前
INote轻量文本编辑器
java·javascript·python·c#
聆风吟º1 天前
CANN hccl 深度解析:异构计算集群通信库的跨节点通信与资源管控实现逻辑
人工智能·wpf·transformer·cann
kylezhao20191 天前
C# 中的 SOLID 五大设计原则
开发语言·c#