c# 获取视频采集卡并实时显示到winform中并设置自动大小
以下是使用C#获取视频采集卡并实时显示到Winform中并设置自动大小的示例代码:
using System;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
namespace VideoCapture
{
public partial class Form1 : Form
{
private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoDevice;
private VideoCapabilities[] videoCapabilities;
private VideoCapabilities[] snapshotCapabilities;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// 获取可用的视频设备
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo device in videoDevices)
{
cbDevices.Items.Add(device.Name);
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (cbDevices.SelectedIndex == -1)
{
MessageBox.Show("请选择视频设备");
return;
}
if (videoDevice == null)
{
// 创建视频采集设备
videoDevice = new VideoCaptureDevice(videoDevices[cbDevices.SelectedIndex].MonikerString);
videoDevice.NewFrame += new NewFrameEventHandler(videoDevice_NewFrame);
}
// 获取可用的视频分辨率
videoCapabilities = videoDevice.VideoCapabilities;
foreach (VideoCapabilities capabilty in videoCapabilities)
{
cbResolutions.Items.Add(capabilty.FrameSize.Width + "x" + capabilty.FrameSize.Height);
}
// 获取可用的截图分辨率
snapshotCapabilities = videoDevice.SnapshotCapabilities;
foreach (VideoCapabilities capabilty in snapshotCapabilities)
{
cbSnapshots.Items.Add(capabilty.FrameSize.Width + "x" + capabilty.FrameSize.Height);
}
// 开始视频采集
videoDevice.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
if (videoDevice != null)
{
// 停止视频采集
videoDevice.Stop();
videoDevice = null;
}
}
private void videoDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
// 显示视频帧
pbVideo.Image = (System.Drawing.Image)eventArgs.Frame.Clone();
// 设置PictureBox自动大小
pbVideo.SizeMode = PictureBoxSizeMode.AutoSize;
}
private void btnSnapshot_Click(object sender, EventArgs e)
{
if (cbSnapshots.SelectedIndex == -1)
{
MessageBox.Show("请选择截图分辨率");
return;
}
// 设置截图分辨率
videoDevice.SnapshotResolution = snapshotCapabilities[cbSnapshots.SelectedIndex];
// 截取当前视频帧
pbSnapshot.Image = (System.Drawing.Image)pbVideo.Image.Clone();
pbSnapshot.SizeMode = PictureBoxSizeMode.AutoSize;
}
}
}
其中,cbDevices是ComboBox控件,用于选择视频设备;cbResolutions和cbSnapshots也是ComboBox控件,分别用于选择视频分辨率和截图分辨率;pbVideo和pbSnapshot是PictureBox控件,分别用于显示实时视频和截图。
在btnStart_Click事件中,创建视频采集设备并开始视频采集;在videoDevice_NewFrame事件中,将视频帧显示到pbVideo控件中,并设置自动大小;在btnSnapshot_Click事件中,设置截图分辨率并截取当前视频帧,将截图显示到pbSnapshot控件中,并设置自动大小。在btnStop_Click事件中,停止视频采集。
可以根据需要对代码进行修改和优化
原文地址: https://www.cveoy.top/t/topic/fjaV 著作权归作者所有。请勿转载和采集!