using AForge.Controls; using AForge.Video.DirectShow; using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; namespace Common.system { public static class CameraHelper { private static FilterInfoCollection _cameraDevices; private static VideoCaptureDevice div = null; private static VideoSourcePlayer sourcePlayer = new VideoSourcePlayer(); private static bool _isDisplay = false; //指示_isDisplay设置为true后,是否设置了其他的sourcePlayer,若未设置则_isDisplay重设为false private static bool isSet = false; /// /// 获取或设置摄像头设备,无设备为null /// public static FilterInfoCollection CameraDevices { get => _cameraDevices; set => _cameraDevices = value; } /// /// 指示是否显示摄像头视频画面 /// 默认false /// public static bool IsDisplay { get => _isDisplay; set => _isDisplay = value; } /// /// 获取或设置VideoSourcePlayer控件, /// 只有当IsDisplay设置为true时,该属性才可以设置成功 /// public static VideoSourcePlayer SourcePlayer { get => sourcePlayer; set { if (_isDisplay) { sourcePlayer = value; isSet = true; } } } /// /// 更新摄像头设备信息 /// public static void UpdateCameraDevices() { _cameraDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); } /// /// 设置使用的摄像头设备 /// /// 设备在CameraDevices中的索引 /// public static bool SetCameraDevice(int index) { if (!isSet) { _isDisplay = false; } //无设备,返回false if (_cameraDevices.Count <= 0 || index < 0) { return false; } if (index > _cameraDevices.Count - 1) { return false; } // 设定初始视频设备 div = new VideoCaptureDevice(_cameraDevices[index].MonikerString); sourcePlayer.VideoSource = div; div.Start(); sourcePlayer.Start(); return true; } /// /// 截取一帧图像并保存 /// /// 图像保存路径 /// 保存的图像文件名 /// 如果保存成功,则返回完整路径,否则为 null public static string CaptureImage(string filePath, string fileName = null) { if (sourcePlayer.VideoSource == null) { return null; } if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } try { Image bitmap = sourcePlayer.GetCurrentVideoFrame(); if (bitmap != null) { if (fileName == null) { fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"); } string fullPath = Path.Combine(filePath, fileName + "-cap.jpg"); System.Drawing.Bitmap objNewPic = new System.Drawing.Bitmap(bitmap, 172, 124);//图片保存的大小尺寸 objNewPic.Save(fullPath, ImageFormat.Jpeg); //bitmap.Save(fullPath, ImageFormat.Jpeg); bitmap.Dispose(); objNewPic.Dispose(); return fullPath; } return null; } catch (Exception) { return null; } } /// /// 关闭摄像头设备 /// public static void CloseDevice() { if (div != null && div.IsRunning) { sourcePlayer.Stop(); div.SignalToStop(); div = null; _cameraDevices = null; } } } }