2017-07-13 29 views
0

我们试图使用MediaCapture类从网络摄像头自动捕获图像。我们正在尝试创建一个应用程序,它可以打开相机,等待片刻并捕获前面的图像,而无需点击屏幕进行拍摄。我们尝试使用LowLagPhotoCapture类,但不能按需要工作。示例代码 -如何使用MediaCapture类打开并自动捕获摄像头

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。请检查!