在 WP8.1 运行时(也在 Silverlight 中)您可以使用 MediaCapture。简而言之:
// First you will need to initialize MediaCapture
Windows.Media.Capture.MediaCapture takePhotoManager = new Windows.Media.Capture.MediaCapture();
await takePhotoManager.InitializeAsync();
如果您需要预览,可以使用CaptureElement:
// In XAML:
<CaptureElement x:Name="PhotoPreview"/>
然后在后面的代码中你可以像这样开始/停止预览:
// start previewing
PhotoPreview.Source = takePhotoManager;
await takePhotoManager.StartPreviewAsync();
// to stop it
await takePhotoManager.StopPreviewAsync();
最后要拍照,例如,您可以将其直接带到文件CapturePhotoToStorageFileAsync 或流CapturePhotoToStreamAsync:
ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
// a file to save a photo
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
"Photo.jpg", CreationCollisionOption.ReplaceExisting);
await takePhotoManager.CapturePhotoToStorageFileAsync(imgFormat, file);
如果你想捕捉视频,那么here is more information。
别忘了在清单文件的Capabilities 中添加Webcam,在Requirements 中添加Front/Rear Camera。
如果您需要选择相机(前/后),您需要获取相机 ID,然后使用所需设置初始化 MediaCapture:
private static async Task<DeviceInformation> GetCameraID(Windows.Devices.Enumeration.Panel desired)
{
DeviceInformation deviceID = (await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture))
.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desired);
if (deviceID != null) return deviceID;
else throw new Exception(string.Format("Camera of type {0} doesn't exist.", desired));
}
async private void InitCamera_Click(object sender, RoutedEventArgs e)
{
var cameraID = await GetCameraID(Windows.Devices.Enumeration.Panel.Back);
captureManager = new MediaCapture();
await captureManager.InitializeAsync(new MediaCaptureInitializationSettings
{
StreamingCaptureMode = StreamingCaptureMode.Video,
PhotoCaptureSource = PhotoCaptureSource.Photo,
AudioDeviceId = string.Empty,
VideoDeviceId = cameraID.Id
});
}