Revision as of 00:21, 21 June 2013 by diegodobelo (Talk | contribs)

Minimal Camera app in Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search

Delete instructional text in italic

This article explains how to ... Replace the abstract text with a short paragraph (or sentence) describing what the topic covers.

Enter article metadata as described below. Note that this template can be placed anywhere in the article. Do not remove parameters that you do not use

WP Metro Icon Multimedia.png
WP Metro Icon WP8.png
WP Metro Icon Baby.png
Article Metadata
Windows Phone 8
Created: diegodobelo (17 Jun 2013)
Last edited: diegodobelo (21 Jun 2013)


The Windows Phone camera is a useful resource to create fancy applications, but sometimes we just need a place to get started. This article shows how to quickly access the camera of a Windows Phone device programatically. It will not use the advanced camera features because the intention here is get the camera working as quick as possible.


Install the Windows Phone 8 SDK: http://dev.windowsphone.com/en-us/downloadsdk

Open Visual Studio. Select file->New Project...

On Templates section select Visual C #-> Windows Phone -> Windows Phone App

Enter the project name and press OK.

Select Windows Phone OS 8.0 as the target Windows Phone OS version and press OK.


In the MainPage.xaml file update the element phone:PhoneApplicationPage to lock the orientation on landscape and to hide the system tray:

SupportedOrientations="Landscape" Orientation="LandscapeLeft" shell:SystemTray.IsVisible="False"

Now delete the <Grid.RowDefinitions> element and add the following canvas element:

<Canvas x:Name="viewfinderCanvas" HorizontalAlignment="Center" >
<!--Camera viewfinder -->
<VideoBrush x:Name="viewfinderBrush" />

Now the MainPage.xaml will look like:

FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Landscape" Orientation="LandscapeLeft"
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Canvas x:Name="viewfinderCanvas" HorizontalAlignment="Center" >
<!--Camera viewfinder -->
<VideoBrush x:Name="viewfinderBrush" />

To create this camera application we need to declare the camera capability in the app manifest file. Open the WMAppManifest.xml file and select ID_CAP_ISV_CAMERA and ID_CAP_MEDIALIB_PHOTO under capabilities tab. They are needed to access the camera and to save a photo on device, respectively. Don't forget to save the file.

Open the MainPage.xaml.cs file and add the following directive at the top of the page:

using Microsoft.Devices;

Add the following variable declaration before the class constructor:

private PhotoCamera _cam;

Now add the following method to the class:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) ||
(PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true))
if (PhotoCamera.IsCameraTypeSupported(CameraType.Primary))
_cam = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
_cam.Initialized += new EventHandler<CameraOperationCompletedEventArgs>(cam_Initialized);
_cam.CaptureImageAvailable += new EventHandler<ContentReadyEventArgs>(cam_CaptureImageAvailable);

This code instantiates the camera object using the primary camera as source. It also set the events handlers to camera initialization and image availability. At the end of the method the camera object is set as the source of viewfinderBrush, which was defined at the MainPage.xaml file as a VideoBrush.

Note that the compiler is complaining about missing cam_Initialized and cam_CaptureImageAvailable methods. It is because they are not implemented yet. We will implement them later.

The camera image is shown into the canvas created in MainPage.xaml called viewfiderCanvas. We had not set the canvas width and height yet. To make this canvas fit the screen of the target device we need to calculate the width and height for the canvas. Let's start adding the following class attributes:

private double _canvasWidth;
private double _canvasHeight;

There are several devices with different screens and aspect ratios. There are also several camera resolutions. A good approach is to calculate the canvas width and height in a way to fit the camera image into the screen without cuts, even if the camera aspect ration doesn't match the screen aspect ratio. To calculate the canvas dimensions we will need to add this method:

private double GetCameraAspectRatio()
IEnumerable<Size> resList = _cam.AvailableResolutions;
if (resList.Count<Size>() > 0)
Size res = resList.ElementAt<Size>(0);
return res.Width / res.Height;
return 1;

It will get the available camera resolutions to calculate the aspect ratio.

Add the cam_Initialized method:

void cam_Initialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e)
if (e.Succeeded)
_canvasHeight = Application.Current.Host.Content.ActualWidth;
_canvasWidth = _canvasHeight * GetCameraAspectRatio();
viewfinderCanvas.Width = _canvasWidth;
viewfinderCanvas.Height = _canvasHeight;

If the camera initialization has succeeded we get the actual screen width and set it as the canvas height value. It is inverted because we are creating the application in landscape mode. With the canvas height we can now calculate the canvas width using the camera aspect ratio.

Now let's add the cam_CaptureImageAvailable. Into this method we will add the code to save the captured picture in camera roll.

First of all add the following directive at the top of the page:

using Microsoft.Xna.Framework.Media;

and add this attribute to the class:

private MediaLibrary _library = new MediaLibrary();

This is the class that saves the image in camera roll. We will use it into cam_CaptureImageAvailable method:

void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
string fileName = "example.jpg";
// Save photo to the media library camera roll.
_library.SavePictureToCameraRoll(fileName, e.ImageStream);
// Close image stream

In this method we set up the filename and then we call the method SavePictureToCameraRoll of MediaLibrary passing the file name and the image stream as parameters. To finalize we close the stream.

Remove Category:Draft when the page is complete or near complete

The "platform categories" will be displayed here in preview only - Copy paste relevant categories into text here

Add categories below using category selector. To see appropriate versions for each platform you can add the {{VersionHint}} template and preview the page. Then copy-paste the ones you want.

320 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.


Thank you!

We appreciate your feedback.