When building WinRT applications you will want to implement the ability to capture images/video’s from the onboard webcamera in order to use in your application. Fortunately for you this is very easy to accomplish. We will walk through how to do this in this post.
Step 1: Enable access to the web camera
The first thing you will need to do is to enable the ‘Webcam’ capability in your application. If you do not do this you will see the following screen when trying to use the webcam API
To enable this capability do this
- Open the Package.appxmanifest
- Click on the capabilities tab
- Check the Webcam item in the list
Step 2: Start to implement the Camera API, basic approach
private async void CapturePicture()
{
var dialog = new CameraCaptureUI();
var file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
// Do something useful w/ the file
}
}
The code above is the least amount you can use to access the webcamera, but we can add a few options to help the user out
Step 3: Allow the user to Crop the image.
When using the API you can toggle a setting which will allow the user to crop the image to fit their own need.
private async void CapturePicture()
{
var dialog = new CameraCaptureUI();
dialog.PhotoSettings.AllowCropping = true;
var file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
// Do something useful w/ the file
}
}
If you set the bool flag you will get the following app bar button
You will also get the crop ‘points’ once you hit the crop button as below

Step 4: Change the max resolution
If you want, you can even change the resolution allowed by your application.
private async void CapturePicture()
{
var dialog = new CameraCaptureUI();
dialog.PhotoSettings.MaxResolution = CameraCaptureUIMaxPhotoResolution.HighestAvailable;
var file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
// Do something useful w/ the file
}
}
When setting the resolution you can pick from many options which are part of the enumeration as shown below:
Step 5: Choosing the format for the image to be saved as
private async void CapturePicture()
{
var dialog = new CameraCaptureUI();
dialog.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Png;
var file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
// Do something useful w/ the file
}
}
When setting the format you can pick from multiple options that are part of the enumeration as shown below:
As you can see using the Camera API can be very basic or you can customize to meet the direct needs of your application, it is all up to you.
Till next time,
Posted
07-06-2012 1:21 PM
by
Derik Whittaker