WPF中經過AForge實現USB攝像頭拍照

最近因爲某種緣由呢,須要作一下拍照的功能,原本我糾結到底用AForge類庫仍是用WPFMediaKit.dll ,不事後來看網上說WPFMediaKit.dll 是截圖而AForge是直接經過攝像頭拍照,因而乎,我就選擇了AForge類庫。express

首先留下發帖時我所用的AForge    連接:https://pan.baidu.com/s/1htmOjPi 密碼:tovdide

第一步spa

  將AForge中的DLL添加進引用,而後添加引用System.Drawing,System.Windows.Forms,WindowsFormsIntegrationcode

第二步orm

  加上視頻

   xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
        xmlns:aforge ="clr-namespace:AForge.Controls;assembly=AForge.Controls"xml

  還有htm

  <wfi:WindowsFormsHost Grid.Row="0" HorizontalAlignment="Left" Width="517" Height="320" VerticalAlignment="Top">
            <aforge:VideoSourcePlayer x:Name="player" Height="480" Width="640"/>
        </wfi:WindowsFormsHost>blog

  下面貼詳細代碼進程

MainWindow.xaml

<Window x:Class="FaceOne.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:FaceOne" xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration" xmlns:aforge ="clr-namespace:AForge.Controls;assembly=AForge.Controls" mc:Ignorable="d" Title="MainWindow" Height="600" Width="800" Loaded="Window_Loaded">
    <Grid>
        <wfi:WindowsFormsHost Grid.Row="0" HorizontalAlignment="Left" Width="517" Height="320" VerticalAlignment="Top">
            <aforge:VideoSourcePlayer x:Name="player" Height="480" Width="640"/>
        </wfi:WindowsFormsHost>
        <Button x:Name="connectBtn" Content="鏈接" HorizontalAlignment="Left" Margin="53,439,0,0" VerticalAlignment="Top" Width="75" Click="connectBtn_Click"/>
        <Button x:Name="captureBtn" Content="拍照" HorizontalAlignment="Left" Margin="180,439,0,0" VerticalAlignment="Top" Width="75" Click="captureBtn_Click"/>
        <Button x:Name="closeBtn" Content="斷開" HorizontalAlignment="Left" Margin="312,439,0,0" VerticalAlignment="Top" Width="75" Click="closeBtn_Click"/>
        <Image x:Name="imageCapture" HorizontalAlignment="Left" Height="210" Margin="522,66,0,0" VerticalAlignment="Top" Width="239"/>

    </Grid>
</Window>

MainWindow.xaml.cs

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; namespace FaceOne { /// <summary>
    /// MainWindow.xaml 的交互邏輯 /// </summary>
    public partial class MainWindow : Window { MyCapture myCapture = MyCapture.Instance(); public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { //myCapture.sourcePlayer = player;//配置好XAML後再加上這句,便可看到攝像頭的視圖
 myCapture.getCamera();//獲取攝像頭
            myCapture.saveOk += ImageSaveOk;//保存照片後觸發
 } //鏈接
        private void connectBtn_Click(object sender, RoutedEventArgs e) { myCapture.CameraConn(); } //拍照
        private void captureBtn_Click(object sender, RoutedEventArgs e) { myCapture.CaputreImage(); } //斷開
        private void closeBtn_Click(object sender, RoutedEventArgs e) { myCapture.CloseDevice(); } //保存照片後觸發(想看預覽就用,不想看就不須要了)
        private void ImageSaveOk(string str) { /*//老套的賦值方式,不會釋放內存 BitmapImage bit = new BitmapImage(); bit.BeginInit(); bit.UriSource = new Uri(AppDomain.CurrentDomain.BaseDirectory+str); bit.EndInit(); imageCapture.Source = bit;*/ BitmapImage bmi = myCapture.InitImage(str); imageCapture.Source = bmi; } } }

MyCapture.cs

using AForge.Controls; using AForge.Video.DirectShow; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media.Imaging; namespace FaceOne { class MyCapture { public delegate void SaveOk(string str); public SaveOk saveOk; private static MyCapture instance; public static MyCapture Instance() { if (instance == null) { instance = new MyCapture(); } return instance; } //private static FilterInfoCollection _cameraDevices;
        private FilterInfoCollection videoDevices; //private static VideoCaptureDevice div = null;
 VideoCaptureDevice videoSource; public VideoSourcePlayer sourcePlayer = new VideoSourcePlayer(); public void getCamera() { // 獲取電腦已經安裝的視頻設備
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); if (videoDevices != null && videoDevices.Count > 0) { foreach (FilterInfo device in videoDevices) { Console.WriteLine(device.Name); } //CameraConn();
 } } //鏈接而且打開攝像頭
        public void CameraConn() { if (videoDevices.Count <= 0) { Console.WriteLine("請插入視頻設備"); return; } videoSource= new VideoCaptureDevice(videoDevices[0].MonikerString);//鏈接到第一個設備,可靈活改動 //videoSource.DesiredFrameSize = new System.Drawing.Size(240, 320); //videoSource.DesiredFrameRate = 1;
 sourcePlayer.VideoSource = videoSource; videoSource.Start(); sourcePlayer.Start(); } //截取一幀圖像並保存
        public void CaputreImage(string filePath=null,string fileName=null) { if (sourcePlayer.VideoSource == null) { return; } //判斷是否有這個目錄,若是沒有則新建立這個目錄
            /*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 str = @"" + fileName + ".jpg"; string str = "asd.jpg";//使用InitImage能夠重複讀寫一張圖,不用的話,就只能一直保存新的圖片了
                bitmap.Save(str,ImageFormat.Jpeg); //想看預覽就用,不想看就不須要了
 bitmap.Dispose(); saveOk(str); } catch(Exception e) { Console.WriteLine(e.Message.ToString()); } } //關閉攝像頭設備
        public void CloseDevice() { if (videoSource != null && videoSource.IsRunning) { sourcePlayer.Stop(); videoSource.SignalToStop(); videoSource = null; videoDevices = null; } } //解決不一樣進程讀取同一張圖片的問題,使用流來讀圖片
        public BitmapImage InitImage(string filePath) { BitmapImage bitmapImage; using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open))) { FileInfo fi = new FileInfo(filePath); byte[] bytes = reader.ReadBytes((int)fi.Length); reader.Close(); //image = new Image();
                bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = new MemoryStream(bytes); bitmapImage.EndInit(); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; //image.Source = bitmapImage;
 reader.Dispose(); } return bitmapImage; } } }
相關文章
相關標籤/搜索