1.打开VS2019,新建一个Form窗体,工具->NuGet包管理工具->管理解决方案的NuGet包,在浏览里搜索AForge.Controls、AForge.Video.DirectShow,安装AForge.Controls和AForge.Video.DirectShow
2.安装AForge组件完成后,VS工具箱会新增AForge控件,把AForge.NET中的VideoSourcePlayer拖到Form窗体上
3.关键代码
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
#region 变量
/// <summary>
/// 摄像头设备集合
/// </summary>
FilterInfoCollection videoDevices;
/// <summary>
/// 捕获设备资源
/// </summary>
VideoCaptureDevice videoSource;
/// <summary>
/// 处理图片
/// </summary>
Bitmap bitImg;
#endregion
/// <summary>
/// 先检测摄像头
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private
void
Form1_Load(
object
sender, EventArgs e)
{
//检测电脑所有的摄像头
videoDevices =
new
FilterInfoCollection(FilterCategory.VideoInputDevice);
MessageBox.Show(
"检测到了【"
+ videoDevices.Count.ToString() +
"】个摄像头"
);
//获取需要拍照的设备
videoSource =
new
VideoCaptureDevice(videoDevices[0].MonikerString);
videoSourcePlayer1.VideoSource = videoSource;
//启动摄像头
videoSourcePlayer1.Start();
}
/// <summary>
/// 拍照
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private
void
button1_Click(
object
sender, EventArgs e)
{
//拍摄并获取图片
bitImg = videoSourcePlayer1.GetCurrentVideoFrame();
}
/// <summary>
/// 关闭摄像头
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private
void
button2_Click(
object
sender, EventArgs e)
{
ShutCamera();
}
/// <summary>
/// 关闭并释放摄像头
/// </summary>
public
void
ShutCamera()
{
if
(videoSourcePlayer1.VideoSource !=
null
)
{
videoSourcePlayer1.SignalToStop();
videoSourcePlayer1.WaitForStop();
videoSourcePlayer1.VideoSource =
null
;
}
}