如何使用MediaCapture类打开和自动捕获相机

时间:2017-07-13 10:03:20

标签: c# xaml uwp xamarin.uwp

我们正尝试使用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 个答案:

答案 0 :(得分:2)

我已完成您提供的代码并达到了您的要求。请参阅以下代码。请注意,您应在Universal Windows Platform(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。请检查!