C#調用本機攝像頭


這段時間一個小項目中需要調用本機的攝像頭進行拍照,網上搜集了一些資料以及解決的一些小問題,在此記錄以便后續使用。

硬件環境:聯想C360一體機,自帶攝像頭

編寫環境:vs2010

語言:C# WPF

 

下載AForge類庫,並添加引用:

using AForge;
using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using Size = System.Drawing.Size;

 

在xaml界面中添加VideoSourcePlayer控件,此次稍微解釋如何添加外來控件:

在工具箱中添加新的選項卡,右鍵添加選擇項,瀏覽選擇控件dll確定,引用控件即可添加到工具箱中。

 

枚舉所有的攝像頭:

復制代碼
FilterInfoCollection videoDevices;
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

foreach (FilterInfo device in videoDevices)
                {
                    //可以做出處理
                }
復制代碼

 

連接攝像頭:

復制代碼
聲明: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;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM