在Windows 8桌面应用上使用MediaCapture

Ray*_*y20 6 c# webcam windows-8 winrt-xaml windows-store-apps

在Windows 8桌面应用程序中,我需要使用C#4.5中的相机拍摄照片.

我曾尝试使用CameraCaptureUI类,但它不适用于桌面应用程序.

所以我尝试使用MediaCapture类,它可用于Metro应用程序或桌面应用程序.它的工作原理非常好,基于此处的示例:http://code.msdn.microsoft.com/windowsapps/media-capture-sample-adf87622/

var capture = new MediaCapture();
// Find the camera device id to use
string deviceId = "";
var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(Windows.Devices.Enumeration.DeviceClass.VideoCapture);
for (var i = 0; i < devices.Count; i++) {
     Console.WriteLine(devices[i]);
     deviceId = devices[i].Id;
}

// init the settings of the capture
var settings = new MediaCaptureInitializationSettings();
settings.AudioDeviceId = "";
settings.VideoDeviceId = deviceId;
settings.PhotoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.Photo;
settings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.Video;
await capture.InitializeAsync(settings);

// Find the highest resolution available
VideoEncodingProperties resolutionMax = null;
int max = 0;
var resolutions = capture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo);
for (var i = 0; i < resolutions.Count; i++) {
     VideoEncodingProperties res = (VideoEncodingProperties)resolutions[i];
     Console.WriteLine("resolution : " + res.Width + "x" + res.Height);
     if (res.Width * res.Height > max) {
          max = (int)(res.Width * res.Height);
          resolutionMax = res;
     }
}
await capture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, resolutionMax);

ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
var fPhotoStream = new InMemoryRandomAccessStream();

// THE 2 LINES I NEED TO ADD
// captureElement.Source = capture;
// await capture.StartPreviewAsync();

// Take the photo and show it on the screen
await capture.CapturePhotoToStreamAsync(imageProperties, fPhotoStream);
await fPhotoStream.FlushAsync();
fPhotoStream.Seek(0);

byte[] bytes = new byte[fPhotoStream.Size];
await fPhotoStream.ReadAsync(bytes.AsBuffer(), (uint)fPhotoStream.Size, InputStreamOptions.None);

BitmapImage bitmapImage = new BitmapImage();
MemoryStream byteStream = new MemoryStream(bytes);
bitmapImage.BeginInit();
bitmapImage.StreamSource = byteStream;
bitmapImage.EndInit();
image.Source = bitmapImage;
Run Code Online (Sandbox Code Playgroud)

我可以使用相机拍照,但拍照前我无法显示预览.为了能够显示预览,我必须使用组件CaptureElement,例如使用以下代码:

captureElement.Source = mediaCapture;
await mediaCapture.startPreviewAsync();
Run Code Online (Sandbox Code Playgroud)

不幸的是,我无法在非商店应用上使用CaptureElement.我可以在WPF或WinForm应用程序中使用另一个组件,以便能够显示摄像头的预览吗?

Wil*_*son 0

拍摄照片后,我执行以下操作:

_ms.Seek(0);
var _bmp = new BitmapImage();
_bmp.SetSource(_ms);
preview1.Source = _bmp;
Run Code Online (Sandbox Code Playgroud)

预览 XAML 控件是

<Image x:Name="preview1" Margin="850,90,102,362" />
Run Code Online (Sandbox Code Playgroud)