WPF 加载摄像机视频
WPF 显示摄像机可以借助AForge进行实现视频显示和数据录制。
视频显示
1.引入AForge库文件
NUGet导入
AForge
AForge.Vedio
AForge.Vedio.DirectShow
2.设置UI
添加一个Image控件,用于视频呈现。
<Window x:Class="Rxbit.Views.Scane.CameraWindow"
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:Rxbit.Views.Scane"
mc:Ignorable="d"
Title="CameraWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel>
<ComboBox Name="SS" DisplayMemberPath="UUYY" SelectedValuePath="Index" SelectionChanged="SS_SelectionChanged"/>
</StackPanel>
<Grid Grid.Row="1" >
<Border BorderBrush="SaddleBrown" BorderThickness="2">
<Image x:Name="ImgCamera" />
</Border>
</Grid>
</Grid>
</Window>
3.通过Aforge获取视频并显示到界面
using AForge.Video;
using AForge.Video.DirectShow;
using Rxbit.Base;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace Rxbit.Views.Scane
{
/// <summary>
/// CameraWindow.xaml 的交互逻辑
/// </summary>
public partial class CameraWindow : Window
{
private FilterInfoCollection videoDevices;
public CameraWindow()
{
InitializeComponent();
Loaded += CameraWindow_Loaded;
Closed += CameraWindow_Closed;
}
private void CameraWindow_Closed(object sender, EventArgs e)
{
try
{
CloseCaptureDevice();
}
catch (Exception)
{
}
}
/// <summary>
/// ComboBox显示类型
/// </summary>
public class CaItem
{
/// <summary>
/// 在videoDevices中的索引,从0开始
/// </summary>
public int Index { get; set; }
/// <summary>
/// 显示的文本
/// </summary>
public string UUYY { get; set; }
}
public List<CaItem> CaItems { get; set; }
private void CameraWindow_Loaded(object sender, RoutedEventArgs e)
{
try
{
// 枚举所有视频输入设备
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count == 0)
throw new ApplicationException();
CaItems = new List<CaItem>();
for (int i = 0; i < videoDevices.Count; i++)
{
CaItems.Add(new CaItem() { Index = i, UUYY = videoDevices[i].Name });
}
SS.ItemsSource = CaItems;
SS.SelectedIndex = 0;
}
catch (ApplicationException)
{
SS.Items.Add("No local capture devices");
videoDevices = null;
}
}
private void myCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
//currentBitmap = bitmap.Clone(
// new RectangleF((bitmap.Size.Width - 640) / 2, (bitmap.Size.Height - 480) / 2, 640, 480), //显示图像的宽度为295像素,高度为413像素
//System.Drawing.Imaging.PixelFormat.Format32bppRgb);
bitmap = bitmap.Clone(
new RectangleF((bitmap.Size.Width - 640) / 2, (bitmap.Size.Height - 480) / 2, 640, 480), //显示图像的宽度为295像素,高度为413像素
System.Drawing.Imaging.PixelFormat.Format32bppRgb);
Thread.Sleep(10);
//mutex.WaitOne();
this.Dispatcher.BeginInvoke(new Action(() =>
{
ImgCamera.Source = ImageSourceForBitmap(bitmap);
}), DispatcherPriority.Background, null);
// mutex.ReleaseMutex();
}
/// <summary>
/// 将Bitmap格式的数据转换成ImageSource
/// 获取 ImageSource 格式的图片
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
public ImageSource ImageSourceForBitmap(Bitmap bmp)
{
var handle = bmp.GetHbitmap();
try
{
ImageSource newsource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
DeleteObject(handle);
return newsource;
}
catch (Exception)
{
DeleteObject(handle);
return null;
}
//finally
//{
// DeleteObject(handle);
//}
}
/// <summary>
/// 删除非托管对象对象
/// </summary>
/// <param name="hObject"></param>
/// <returns></returns>
[DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteObject([In] IntPtr hObject);
/// <summary>
/// 关闭设备
/// </summary>
public void CloseCaptureDevice()
{
if (myCaptureDevice != null)
{
if (myCaptureDevice.IsRunning)
{
myCaptureDevice.SignalToStop();
}
myCaptureDevice = null;
}
}
/// <summary>
/// 摄像机
/// </summary>
VideoCaptureDevice myCaptureDevice;
bool sst = true;
private void SS_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int a = Convert.ToInt32((sender as ComboBox).SelectedValue.ToString());
CloseCaptureDevice();
myCaptureDevice = new VideoCaptureDevice(videoDevices[a].MonikerString);//myCaptureDevice的类型为VideoCaptureDevice,
myCaptureDevice.NewFrame += new NewFrameEventHandler(myCaptureDevice_NewFrame);
myCaptureDevice.DesiredFrameSize = new System.Drawing.Size(640, 480);//436, 360
myCaptureDevice.DesiredFrameRate = 60;
myCaptureDevice.Start();
}
}
}