WPF连接USB相机,拍照,视频 示例
USB相机连接
项目通过AForge库实现WPF 连接相机,进行拍照录像。
安装 AForge 库
在NuGet 中下载安装这三个包
AForge.Video
AForge.Control
AForge.Video.DirectShow
代码示例
辅助类 CameraHelper.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
<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
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();
}
}
}
实现效果
左边是实时录像,右边是拍照定格,且照片可保存