C# 访问摄像头并拍照
在C#中,您可以使用System.Drawing和AForge.Video库来访问摄像头并拍照。以下是一个简单的示例,演示如何在C#中访问摄像头并拍照:
using System;
using System.Drawing;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
class Program
{
private static FilterInfoCollection videoDevices;
private static VideoCaptureDevice videoSource;
static void Main()
{
// 获取可用的视频设备
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count == 0)
{
Console.WriteLine("未找到可用的摄像头");
return;
}
// 创建视频捕获设备
videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
// 设置视频源的 NewFrame 事件处理程序
videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
// 开始捕获视频
videoSource.Start();
// 等待用户按下 Enter 键
Console.WriteLine("按下 Enter 键拍照");
Console.ReadLine();
// 停止捕获视频
videoSource.SignalToStop();
videoSource.WaitForStop();
}
private static void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
// 获取当前帧图像
Bitmap frame = (Bitmap)eventArgs.Frame.Clone();
// 显示当前帧图像
using (var form = new Form())
{
form.ClientSize = frame.Size;
form.BackgroundImage = frame;
form.ShowDialog();
}
// 保存当前帧图像为文件
string fileName = "photo.jpg";
frame.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
Console.WriteLine("已保存照片: " + fileName);
}
}
在上面的示例中,我们使用FilterInfoCollection类获取可用的视频设备(摄像头)。然后,我们创建一个VideoCaptureDevice实例,指定要使用的摄像头设备。我们设置了NewFrame事件处理程序,该处理程序在每个新的视频帧可用时被调用。在事件处理程序中,我们获取当前帧图像,并显示在一个临时的窗口中。我们还将当前帧图像保存为JPEG文件。
请确保在运行示例之前,将AForge.Video和AForge.Video.DirectShow库添加到您的项目中。
上一篇:C# 调用摄像头识别二维码