参考:
【C#】#100 调用摄像头 - 那年、仲夏 - 博客园 (cnblogs.com)
先随便开一个界面
点开那个NuGet程序包选项
浏览里面搜索SForge,下载那些包
下载好了
代码来自第二篇博客,仅仅作为学习记录,刚开始学习C#,从看代码开始
他页面的设计:
第一步是枚举所有相机,我所理解的就是这个函数是新加载Form1的时候就会调用,里面的语法和C++类似
private void Form1_Load(object sender, EventArgs e)
{
try
{
// 枚举所有视频输入设备
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count == 0)
throw new ApplicationException();
foreach (FilterInfo device in videoDevices)
{
tscbxCameras.Items.Add(device.Name);
}
tscbxCameras.SelectedIndex = 0;
}
catch (ApplicationException)
{
tscbxCameras.Items.Add("No local capture devices");
videoDevices = null;
}
}
第二步连接摄像头 ,也就是点击那个连接按钮的响应函数
private void toolStripButton1_Click(object sender, EventArgs e)
{
CameraConn();
}
//连接摄像头
private void CameraConn()
{
VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[tscbxCameras.SelectedIndex].MonikerString);
videoSource.DesiredFrameSize = new Size(320, 240);
videoSource.DesiredFrameRate = 1;
videPlayer.VideoSource = videoSource;
videPlayer.Start();
}
点击关闭的响应函数
private void toolStripButton2_Click(object sender, EventArgs e)
{
videPlayer.SignalToStop();
videPlayer.WaitForStop();
}
这个应该是点击红色叉的响应函数 ,自动调用上面那个函数,关闭相机
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
toolStripButton2_Click(null, null);
}
这个应该是点击保存图片的响应函数
private void toolStripButton3_Click(object sender, EventArgs e)
{
System.Drawing.Image img = new Bitmap(videPlayer.Width, videPlayer.Height);
videPlayer.DrawToBitmap((Bitmap)img, new Rectangle(0, 0, videPlayer.Width, videPlayer.Height));
img.Save(@"E:/a.bmp",ImageFormat.Bmp);
}