項目中用到 usb 攝像頭,需要根據情況進行圖像抓拍,查了半天資料,比較多的是使用 wpfmediakit 和 aforge 。
但是由于項目要求不顯示 usb 攝像頭拍攝的畫面,最終確定使用 aforge 解決。
下面用一個測試程序記錄一下。
一、無預覽拍照
首先建立一個 wpf 項目,我的就叫 aforgetest,你們隨意就好:
然后在 nuget 包管理器中安裝 aforge 庫:
我只安裝了圖中打勾的幾個庫,這個根據自己項目需要安裝就好。
不過用 usb 攝像頭拍照必須安裝:
aforge.video
aforge.control
aforge.video.directshow
這三個庫文件。
不習慣使用 nuget 也可以到 aforge 的 .net lib 下載頁面下載。
在 mainwindow.xaml 文件中添加兩個按鈕:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
< window x:class = "aforgetest.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:aforgetest" mc:ignorable = "d" title = "mainwindow" height = "300" width = "300" closing = "window_closing" > < stackpanel > < button name = "btncapture" click = "btncapture_click" >拍照</ button > < button name = "btnopencamera" click = "btnopencamera_click" >打開</ button > </ stackpanel > </ window > |
后臺交互邏輯如下:
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
|
using system; using system.windows; namespace aforgetest { /// <summary> /// mainwindow.xaml 的交互邏輯 /// </summary> public partial class mainwindow : window { public mainwindow() { initializecomponent(); } private void btnopencamera_click( object sender, eventargs e) { camerahelper.updatecameradevices(); if (camerahelper.cameradevices.count > 0) { camerahelper.setcameradevice(0); } } private void btncapture_click( object sender, eventargs e) { camerahelper.captureimage( @"e:\1" ); } private void window_closing( object sender, system.componentmodel.canceleventargs e) { camerahelper.closedevice(); } } } |
camerahelper 類代碼如下:
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
|
using system; using aforge.video.directshow; using aforge.controls; using system.windows; using system.io; using system.drawing; using system.drawing.imaging; namespace aforgetest { public static class camerahelper { private static filterinfocollection _cameradevices; private static videocapturedevice div = null ; private static videosourceplayer sourceplayer = new videosourceplayer(); private static bool _isdisplay = false ; //指示_isdisplay設置為true后,是否設置了其他的sourceplayer,若未設置則_isdisplay重設為false private static bool isset = false ; /// <summary> /// 獲取或設置攝像頭設備,無設備為null /// </summary> public static filterinfocollection cameradevices { get { return _cameradevices; } set { _cameradevices = value; } } /// <summary> /// 指示是否顯示攝像頭視頻畫面 /// 默認false /// </summary> public static bool isdisplay { get { return _isdisplay; } set { _isdisplay = value; } } /// <summary> /// 獲取或設置videosourceplayer控件, /// 只有當isdisplay設置為true時,該屬性才可以設置成功 /// </summary> public static videosourceplayer sourceplayer { get { return sourceplayer; } set { if (_isdisplay) { sourceplayer = value; isset = true ; } } } /// <summary> /// 更新攝像頭設備信息 /// </summary> public static void updatecameradevices() { _cameradevices = new filterinfocollection(filtercategory.videoinputdevice); } /// <summary> /// 設置使用的攝像頭設備 /// </summary> /// <param name="index">設備在cameradevices中的索引</param> /// <returns><see cref="bool"/></returns> public static bool setcameradevice( int index) { if (!isset) _isdisplay = false ; //無設備,返回false if (_cameradevices.count <= 0 || index < 0) return false ; if (index > _cameradevices.count - 1) return false ; // 設定初始視頻設備 div = new videocapturedevice(_cameradevices[index].monikerstring); sourceplayer.videosource = div; div.start(); sourceplayer.start(); return true ; } /// <summary> /// 截取一幀圖像并保存 /// </summary> /// <param name="filepath">圖像保存路徑</param> /// <param name="filename">保存的圖像文件名</param> public static void captureimage( string filepath, string filename = null ) { if (sourceplayer.videosource == null ) return ; if (!directory.exists(filepath)) { directory.createdirectory(filepath); } try { //sourceplayer.start(); image bitmap = sourceplayer.getcurrentvideoframe(); if (filename == null ) filename = datetime.now.tostring( "yyyy-mm-dd-hh-mm-ss" ); bitmap.save(filepath + @"\" + filename + "-cap.jpg", imageformat.jpeg); bitmap.dispose(); //sourceplayer.stop(); } catch (exception e) { messagebox.show(e.message.tostring()); } } /// <summary> /// 關閉攝像頭設備 /// </summary> public static void closedevice() { if (div != null && div.isrunning) { sourceplayer.stop(); div.signaltostop(); div = null ; _cameradevices = null ; } } } } |
最終效果如下:
首先單擊打開按鈕,然后單擊拍照按鈕,就會在指定路徑下生成一個 jpg 文件。
單擊打開按鈕之后需要等待 2s 以上才能點擊拍照(需要等待連接到攝像頭),否則會報出異常,如下圖:
二、顯示攝像頭拍攝畫面和截取的圖片
首先添加 system.windows.forms 和 windowsformsintegration 的引用。
然后在 mainwindows.xmal 文件中加命名空間:
1
2
|
xmlns:wfi ="clr-namespace:system.windows.forms.integration;assembly=windowsformsintegration" xmlns:aforge ="clr-namespace:aforge.controls;assembly=aforge.controls"12 |
添加 videosourceplayer 和 image 控件:
1
2
3
|
< wfi:windowsformshost grid.row = "0" > < aforge:videosourceplayer x:name = "player" height = "480" width = "640" /> </ wfi:windowsformshost > |
1
|
< image grid.row = "0" grid.column = "1" name = "imgcapture" stretch = "fill" height = "480" width = "640" /> |
這里有個小細節,注意對 videosourceplayer 命名時,一定要使用 x:name 不要省略 x: ,否則無法在后臺代碼中使用(不要問我是怎么知道的)。
對 camerahelper.cs 中的 captureimage 函數做一點修改:
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
|
/// <summary> /// 截取一幀圖像并保存 /// </summary> /// <param name="filepath">圖像保存路徑</param> /// <param name="filename">保存的圖像文件名</param> /// <returns>如果保存成功,則返回完整路徑,否則為 null</returns> public static string captureimage( string filepath, string filename = null ) { if (sourceplayer.videosource == null ) return null ; 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 fullpath = path.combine(filepath, filename + "-cap.jpg" ); bitmap.save(fullpath, imageformat.jpeg); bitmap.dispose(); return fullpath; } catch (exception e) { messagebox.show(e.message.tostring()); return null ; } } |
修改后臺代碼如下:
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
|
using system; using system.windows; using system.windows.media.imaging; namespace aforgetest { /// <summary> /// mainwindow.xaml 的交互邏輯 /// </summary> public partial class mainwindow : window { public mainwindow() { initializecomponent(); camerahelper.isdisplay = true ; camerahelper.sourceplayer = player; camerahelper.updatecameradevices(); } private void btnopencamera_click( object sender, eventargs e) { if (camerahelper.cameradevices.count > 0) { camerahelper.setcameradevice(0); } } private void btncapture_click( object sender, eventargs e) { string fullpath = camerahelper.captureimage(appdomain.currentdomain.basedirectory + @"\capture" ); bitmapimage bit = new bitmapimage(); bit.begininit(); bit.urisource = new uri(fullpath); bit.endinit(); imgcapture.source = bit; } private void window_closing( object sender, system.componentmodel.canceleventargs e) { camerahelper.closedevice(); } } } |
最終結果如下:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/luo_5458/article/details/74452534