C#使用AForge获取摄像头的图片在不使用控件的情况下。首先新建一个控制台项目,并在Nuget中搜索引入 :aforge和AForge.Video,接着编写示例代码如下:
public class CameraPrivoder
{
private VideoCaptureDevice _videoCaptureDevice;
private bool _isCaptured;
private Bitmap _orgBmp;
private Timer _delayTimer = new Timer(1000);
private object _captureLock = new object();
private object _imgLock = new object();
public Image Take(ushort index = 0)
{
lock (_captureLock)
{
_isCaptured = false;
Connect(index);
int capIndex = 0;
while (_isCaptured == false && capIndex < 50)
{
capIndex++;
System.Threading.Thread.Sleep(100);
}
Close();
return _orgBmp;
}
}
private bool Connect(ushort index = 0)
{
try
{
var videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count == 0)
{
return false;
}
_videoCaptureDevice = new VideoCaptureDevice(videoDevices[index].MonikerString);
var videoCapabilities = _videoCaptureDevice.VideoCapabilities;
//foreach (var video in videoCapabilities)
//{
// LogHelper.Info("预览分辨率->" + video.FrameSize.Width + "*" + video.FrameSize.Height);
//}
if (videoCapabilities.Count() > 0)
_videoCaptureDevice.VideoResolution = _videoCaptureDevice.VideoCapabilities.Last();
//var snapVabalities = _videoCaptureDevice.SnapshotCapabilities;
//foreach (var snap in snapVabalities)
//{
// LogHelper.Info("抓拍分辨率->" + snap.FrameSize.Width + "*" + snap.FrameSize.Height);
//}
//if (snapVabalities.Count() > 0)
// _videoCaptureDevice.SnapshotResolution = _videoCaptureDevice.SnapshotCapabilities.Last();
_videoCaptureDevice.NewFrame += new NewFrameEventHandler(CaptureVideoFrame);
_videoCaptureDevice.Start();
return true;
}
catch (Exception ex)
{
//_logger.Error(ex);
}
return false;
}
private void CaptureVideoFrame(object sender, NewFrameEventArgs eventArgs)
{
try
{
if (_isCaptured)
return;
lock (_imgLock)
{
Stopwatch sw = new Stopwatch();
var bmp = (System.Drawing.Bitmap)eventArgs.Frame.Clone();
sw.Start();
while ( sw.Elapsed.TotalSeconds < 10)
{
System.Threading.Thread.Sleep(100);
bmp = (System.Drawing.Bitmap)eventArgs.Frame.Clone();
}
sw.Stop();
_orgBmp = bmp;
_isCaptured = true;
}
}
catch (Exception ex)
{
//_logger.Error(ex);
}
finally
{
_isCaptured = true;
}
}
private bool Close()
{
bool result = false;
try
{
if (_videoCaptureDevice != null)
{
_videoCaptureDevice.NewFrame -= new NewFrameEventHandler(CaptureVideoFrame);
_videoCaptureDevice.SignalToStop();
//_videoCaptureDevice.WaitForStop();
_videoCaptureDevice = null;
}
result = true;
}
catch (Exception ex)
{
//_logger.Error(ex);
result = false;
}
return result;
}
}
使用方法:
CameraPrivoder cameraPrivoder = new CameraPrivoder();
var image = cameraPrivoder.Take();
其中以上方法支持USB摄像头,Take方法中的index代表视频设备的序号,当有多个视频设备此参数有用。
提示源代码如下:链接:https://pan.baidu.com/s/1c73T-RfOQu8fEUwldLXGHg
💰 此内容为付费阅读 请先登录