<Window x:Class="WpfApp1.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:WpfApp1" xmlns:WPFMediaKit="clr-namespace:WPFMediaKit.DirectShow.Controls;assembly=WPFMediaKit" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <StackPanel> <ComboBox Name="cbCameras" SelectionChanged="cbCameras_SelectionChanged"/> <!--选摄像头--> <WPFMediaKit:VideoCaptureElement Height="200" x:Name="captureElement"/> <!--预览画面--> <Button Height="50" x:Name="btnCapture" Content="拍照" Click="btnCapture_Click"/> <!--拍照按钮--> <Image x:Name="img" /> </StackPanel> </Grid> </Window>
using System; using System.Collections.Generic; using System.Linq; using System.Text; 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.Navigation; using System.Windows.Shapes; using System.Runtime.InteropServices; using WPFMediaKit.DirectShow.Controls; using System.IO; namespace WpfApp1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Loaded += MainWindow_Loaded; } private void MainWindow_Loaded(object sender, RoutedEventArgs e) { cbCameras.ItemsSource = MultimediaUtil.VideoInputNames; if (MultimediaUtil.VideoInputNames.Length > 0) { cbCameras.SelectedIndex = 0; } else { MessageBox.Show("no video cap device"); } } private void cbCameras_SelectionChanged(object sender, SelectionChangedEventArgs e) { captureElement.VideoCaptureSource = (string)cbCameras.SelectedItem; } /// <summary> /// 拍照 /// </summary> private void btnCapture_Click(object sender, RoutedEventArgs e) { //captureElement. 怎么抓取高清的原始图像 RenderTargetBitmap bmp = new RenderTargetBitmap( (int)captureElement.ActualWidth, (int)captureElement.ActualHeight, 96, 96, PixelFormats.Default); //为避免抓不全的情况,需要在Render之前调用Measure、Arrange //为避免VideoCaptureElement显示不全,需要把 //VideoCaptureElement的Stretch="Fill" captureElement.Measure(captureElement.RenderSize); captureElement.Arrange(new Rect(captureElement.RenderSize)); bmp.Render(captureElement); //这里需要创建一个流以便存储摄像头拍摄到的图片。 //当然,可以使文件流,也可以使内存流。 BitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); MemoryStream ms = new System.IO.MemoryStream(); encoder.Save(ms); ms.Position = 0; BitmapImage b = new BitmapImage(); b.BeginInit(); b.StreamSource = ms; b.EndInit(); img.Source = b; ms.Position = 0; FileStream f = File.Open("c:\\1.jpg", FileMode.OpenOrCreate); f.Write(ms.ToArray(), 0, (int)ms.Length); f.Close(); } } }