C# 访问摄像头并拍照

C# 访问摄像头并拍照

编码文章call10242025-01-13 10:27:3029A+A-

在C#中,您可以使用System.DrawingAForge.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.VideoAForge.Video.DirectShow库添加到您的项目中。

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4