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

实现效果

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

相关推荐
步、步、为营41 分钟前
C# 与 Windows API 交互的“秘密武器”:结构体和联合体
windows·c#·交互
omegayy1 小时前
.NET framework、Core和Standard都是什么?
unity·c#·.net
sukalot1 小时前
windows C#-泛型接口
开发语言·c#
大雄野比2 小时前
Rubyer-WPF:打造优雅、精致的 WPF 用户界面
ui·wpf
新中地GIS开发老师4 小时前
80个Three.js 3D模型资源
javascript·数码相机·3d·arcgis·three.js·gis开发·地信
青春~飞鸟4 小时前
从光子到图像——相机如何捕获世界?
图像处理·数码相机·计算机视觉
Damon小智4 小时前
C#进阶-在Ubuntu上部署ASP.NET Core Web API应用
linux·nginx·c#·asp.net·.net·.net core
csdn_aspnet4 小时前
C# 或 .NetCore 如何使用 NPOI 导出图片到 Excel 文件
c#·excel·.netcore
吉量*6 小时前
WPF系列九:图形控件EllipseGeometry
wpf·上位机·绘图·ellipsegeometry
步、步、为营6 小时前
WPF设计时特性加速界面设计
wpf