如何使用 MediaCapture 类打开和自动捕获相机
Posted
技术标签:
【中文标题】如何使用 MediaCapture 类打开和自动捕获相机【英文标题】:How to open and auto capture camera using MediaCapture class 【发布时间】:2017-12-18 01:09:07 【问题描述】:我们正在尝试使用 MediaCapture 类从网络摄像头自动捕获图像。我们正在尝试创建一个应用程序,它可以打开相机,等待片刻,然后在没有人点击屏幕进行捕捉的情况下捕捉它前面的图像。我们尝试使用 LowLagPhotoCapture 类,但无法正常工作。示例代码 -
async private void InitMediaCapture()
MediaCapture _mediaCapture = new MediaCapture();
await _mediaCapture.InitializeAsync();
_displayRequest.RequestActive();
PreviewControlCheckIn.Source = _mediaCapture;
await _mediaCapture.StartPreviewAsync();
await Task.delay(500);
CaptureImage();
async private void CaptureImage()
storeFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync ("TestPhoto.jpg",CreationCollisionOption.GenerateUniqueName);
ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
await _mediaCapture.CapturePhotoToStorageFileAsync(imgFormat, storeFile);
await _mediaCapture.StopPreviewAsync();
任何信息都会很棒,在此先感谢您的帮助。
【问题讨论】:
【参考方案1】:我已完成您提供的代码并达到您的要求。请参考以下代码。请注意,您应该在通用 Windows 平台 (UWP) 应用的程序包清单中声明相机和麦克风功能以访问特定 API。
async private void InitMediaCapture()
_mediaCapture = new MediaCapture();
var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);
var settings = new MediaCaptureInitializationSettings VideoDeviceId = cameraDevice.Id ;
await _mediaCapture.InitializeAsync(settings);
_displayRequest.RequestActive();
PreviewControl.Source = _mediaCapture;
await _mediaCapture.StartPreviewAsync();
var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
_captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
await Task.Delay(500);
CaptureImage();
async private void CaptureImage()
var storeFile = await _captureFolder.CreateFileAsync("PreviewFrame.jpg", CreationCollisionOption.GenerateUniqueName);
ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
await _mediaCapture.CapturePhotoToStorageFileAsync(imgFormat, storeFile);
await _mediaCapture.StopPreviewAsync();
private static async Task<DeviceInformation> FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel)
// Get available devices for capturing pictures
var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
// Get the desired camera by panel
DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);
// If there is no device mounted on the desired panel, return the first device found
return desiredDevice ?? allVideoDevices.FirstOrDefault();
照片将被保存到Pictures
图库。我已经将code sample 上传到 github。请检查!
【讨论】:
以上是关于如何使用 MediaCapture 类打开和自动捕获相机的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Windows MediaCapture API 捕获“仅音频”?