這段時間一個小項目中須要調用本機的攝像頭進行拍照,網上搜集了一些資料以及解決的一些小問題,在此記錄以便後續使用。ide
硬件環境:聯想C360一體機,自帶攝像頭工具
編寫環境:vs2010this
語言:C# WPFspa
下載AForge類庫,並添加引用:3d
using AForge; using AForge.Controls; using AForge.Video; using AForge.Video.DirectShow; using Size = System.Drawing.Size;
在xaml界面中添加VideoSourcePlayer控件,這次稍微解釋如何添加外來控件:code
在工具箱中添加新的選項卡,右鍵添加選擇項,瀏覽選擇控件dll肯定,引用控件便可添加到工具箱中。orm
枚舉全部的攝像頭:視頻
FilterInfoCollection videoDevices; videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); foreach (FilterInfo device in videoDevices) { //能夠作出處理 }
鏈接攝像頭:blog
聲明:FileterInfo info;
info = videoDevices[0];//選取第一個,此處可做靈活改動
VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[info.MonikerString); videoSource.DesiredFrameSize = new System.Drawing.Size(214, 281); videoSource.DesiredFrameRate = 1; videoSourcePlayer.VideoSource = videoSource; videoSourcePlayer.Start();
關閉攝像頭:資源
videoSourcePlayer.SignalToStop();
videoSourcePlayer.WaitForStop();
拍照:
if (videoSourcePlayer.IsRunning) {
string path = "e:\" BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( videoSourcePlayer.GetCurrentVideoFrame().GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); PngBitmapEncoder pE = new PngBitmapEncoder(); pE.Frames.Add(BitmapFrame.Create(bitmapSource)); string picName = path + "paizhao" + ".jpg"; if (File.Exists(picName)) { File.Delete(picName); } using (Stream stream = File.Create(picName)) { pE.Save(stream); } }
項目中要求是攝像頭處於監控狀態,拍照後畫面固定存儲,不滿意能夠清空再次進行拍照,直到滿意爲止。
作法是在videoSourcePlayer的上面添加一個image控件,由於項目是WPF作的,全部照片顯示只能添加image控件,有兩點須要注意:
1)WPF引用winform控件須要使用WindowsFormsHost控件,因此監控視頻和照片顯示時是控件WindowsFormsHost和image控件的顯示和隱藏,此處走了一段彎路因此記錄下來。
2)image控件的source已經綁定,可是照片須要清空刪除該照片資源,系統提示的大體意思是資源已經被佔用沒法刪除。解決途徑:
聲明:BitmapImage bmi = new System.Windows.Media.Imaging.BitmapImage();
使用時:bmi.BgeinInit();
bmi.UriSource = new Uri(picName);
bmi.CacheOption = BitmapCacheOption.OnLoad;
bmi.EndInit();
綁定:this.image.Source = bmi;