基于C#的Aforge類調用簡單示例,供大家參考,具體內容如下
由題,本程序是使用Aforge類庫調用攝像頭的demo。
功能:
1.預覽
2.前后攝像頭切換
1.判斷是否有攝像頭,無則提示
2.有,判斷攝像頭個數,有1個則直接打開預覽
3.有2個或以上,提示選擇后打開相應攝像頭預覽
3.拍照功能
控件:
1.攝像頭列表下拉框:用于選擇攝像頭,如無攝像頭則不能下拉
2.拍照按鈕:用于拍照,照片默認存儲在當前程序運行目錄,名稱為“Aforge.bmp”。如無攝像頭則不能點擊
3.預覽按鈕:用于打開當前選擇攝像頭預覽,如當前選擇攝像頭不變,則不進行重新預覽。如沒有攝像頭則不能點擊
4.提示標簽:用于給出軟件的一些提示
5.預覽控件videoSourcePlayer:用于預覽拍照界面以及實現拍照功能
該控件需要右擊工具箱-選擇項-.NET選項卡中-瀏覽,找到Aforge.Controls.dll庫添加后才會出現
程序設計
1.加載窗體
查找所有攝像頭設備
2.預覽按鈕:
根據選中攝像頭打開該攝像頭并預覽
3.拍照按鈕:
記錄當前幀保存為圖像
代碼
程序主要代碼:
添加引用 using AForge.Video.DirectShow;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
///查找所有攝像頭設備 private void loadCameraList() { VideoCaptureDevice cameraDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); if (cameraDevices.Count == 0) { capture_btn.Enabled = false ; cameraId_cob.Enabled = false ; preview_btn.Enabled = false ; guide_lab.Text = noCameraDevice; cameraDevices = null ; } else if (cameraDevices.Count == 1) { isSingleCamera = true ; preview_btn.Enabled = false ; guide_lab.Visible = false ; } foreach (FilterInfo cameraDevice in cameraDevices) { cameraId_cob.Items.Add(cameraDevice.Name); cameraId_cob.SelectedIndex = 0; } } ///根據選中攝像頭打開該攝像頭并預覽 private VideoCaptureDevice cameraDevice; private void preview() { if ( null != cameraDevice) { //在2個或以上攝像頭進行切換時執行 preview_player.SignalToStop(); preview_player.WaitForStop(); } cameraDevice = new VideoCaptureDevice(cameraDevices[cameraId_cob.SelectedIndex].MonikerString); cameraDevice.DesiredFrameSize = new Size(320, 240); cameraDevice.DesiredFrameRate = 1; preview_player.VideoSource = cameraDevice; preview_player.Start(); } ///記錄當前幀保存為圖像 private void takePhoto() { if (cameraDevice == null ) return ; Bitmap bitmap = preview_player.GetCurrentVideoFrame(); string fullPath = Application.StartupPath + "\\" ; if (!Directory.Exists(fullPath)) Directory.CreateDirectory(fullPath); string img = fullPath + "Aforge.jpg" ; bitmap.Save(img); guide_lab.Text = img; guide_lab.Visible = true ; } |
備注
1.關閉窗體時需要關閉控件:
1
2
3
4
5
|
private void aforgeForm_FormClosing( object sender, FormClosingEventArgs e) { preview_player.SignalToStop(); preview_player.WaitForStop(); } |
2.調用preview_player.GetCurrentVideoFrame()方法提示沒有該方法
由于使用的Aforge.Controls.dll庫版本過低導致,根據官方記錄,該方法需要 (in AForge.Controls.dll) Version: 2.2.5.0 (2.2.5.0)版本支持
3.在添加預覽控件videoSourcePlayer時提示沒有可以加入的控件
目前筆者遇到的這個問題比較奇葩,使用AForge.Controls.dll Version: 2.2.5.0 庫文件添加會報這個錯誤,看過各種解法,比如直接把庫文件拖到工具面板上,還是沒能解決。說奇葩是因為目前親測到的解決方法步驟是:
1).引用那邊先不要添加AForge.Controls.dll文件
2).找到AForge.Controls.dll Version: 2.0.0.0 注意版本號是低版本的。將這個低版本的加入工具面板就可以看到預覽控件videoSourcePlayer。
3).但是,此時代碼里會出現第二個錯誤(調用preview_player.GetCurrentVideoFrame()方法提示沒有該方法)。原因就不解釋了,解決方法是:在引用里面的AForge.Controls.dll(這個時候可以看下屬性是Version: 2.0.0.0)刪除這個舊版本,添加新的版本的AForge.Controls.dll Version: 2.2.5.0。
至此,大功告成。可以正常編譯了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_36957825/article/details/53636430