2017-07-13 45 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。請檢查!