添加程序集:WPFMediaKit.dll
更关键代码如下:
界面设计代码如下:
<Window x:Class="摄像头调用.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="600" Width="800" xmlns:wpfmedia="clr-namespace:WPFMediaKit.DirectShow.Controls;assembly=WPFMediaKit" WindowStartupLocation="CenterScreen" > <Grid> <StackPanel Orientation="Vertical"> <StackPanel Orientation="Horizontal"> <ComboBox Name="cb" SelectionChanged="cb_SelectionChanged" Width="100" ></ComboBox> <Button Width="80" Content="拍" Name="btnCapture" Click="btnCapture_Click" Margin="200,0,0,0"></Button> <Button Width="80" Content="重拍" Name="btnReStart" Click="Restart_Click"></Button> </StackPanel> <wpfmedia:VideoCaptureElement Height="434" x:Name="vce" Stretch="Fill" Margin="172,30,185,0" RenderTransformOrigin="0.5,0.5" > <wpfmedia:VideoCaptureElement.RenderTransform> <TransformGroup> <ScaleTransform/> <SkewTransform/> <RotateTransform Angle="-90"/> <TranslateTransform/> </TransformGroup> </wpfmedia:VideoCaptureElement.RenderTransform> </wpfmedia:VideoCaptureElement> </StackPanel> </Grid> </Window>
处理事件代码
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using System.IO; using WPFMediaKit.DirectShow.Controls; namespace 摄像头调用 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); cb.ItemsSource = MultimediaUtil.VideoInputNames;//获得所有摄像头 if (MultimediaUtil.VideoInputNames.Length > 0) { cb.SelectedIndex = 0;//第0个摄像头为默认摄像头 } else { MessageBox.Show("电脑没有安装任何可用摄像头"); } } private void btnCapture_Click(object sender, RoutedEventArgs e)//拍照 { RenderTargetBitmap bmp = new RenderTargetBitmap((int)vce.ActualWidth, (int)vce.ActualHeight, //vce是前台wpfmedia控件的name 96, 96, PixelFormats.Default); //为避免抓不全的情况,需要在Render之前调用Measure、Arrange //为避免VideoCaptureElement显示不全,需要把 //VideoCaptureElement的Stretch="Fill" vce.Measure(vce.RenderSize); vce.Arrange(new Rect(vce.RenderSize)); bmp.Render(vce); BitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); using (MemoryStream ms = new MemoryStream()) { encoder.Save(ms); byte[] captureData = ms.ToArray(); File.WriteAllBytes(@"./photo/" + Guid.NewGuid().ToString().Substring(0, 5) + ".jpg", captureData); } vce.Pause(); } //重拍 private void Restart_Click(object sender, RoutedEventArgs e) { vce.Play(); } private void cb_SelectionChanged(object sender, SelectionChangedEventArgs e)//ComboBox控件的选择事件 { vce.VideoCaptureSource = (string)cb.SelectedItem;//vce是前台wpfmedia控件的name } } }