×
Namespaces

Variants
Actions

Minimal Camera app in Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search

This article shows the minimum code needed to use the Windows Phone camera in a XAML/C# application. It does not demonstrate more advanced camera features: these would be the feature of articles that build on this topic.

WP Metro Icon Multimedia.png
WP Metro Icon WP8.png
WP Metro Icon Baby.png
Article Metadata
Code Example
Source file: File:CameraApp.zip
Tested with
Devices(s): Nokia Lumia 620
Compatibility
Platform(s): Windows Phone 8 and later
Windows Phone 8
Platform Security
Capabilities: ID_CAP_ISV_CAMERA, ID_CAP_MEDIALIB_PHOTO
Article
Created: diegodobelo (17 Jun 2013)
Last edited: hamishwillee (04 Jul 2013)

Contents

Setup

  1. Install the Windows Phone 8 SDK
  2. Open Visual Studio. Select File | New Project...
  3. On Templates section select Visual C #-> Windows Phone -> Windows Phone App
  4. Enter the project name and press OK.
  5. Select Windows Phone OS 8.0 as the target Windows Phone OS version and press OK.


The XAML

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 -->
<Canvas.Background>
<VideoBrush x:Name="viewfinderBrush" />
</Canvas.Background>
</Canvas>

Now the MainPage.xaml will look like:

<phone:PhoneApplicationPage
x:Class="CameraApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Landscape" Orientation="LandscapeLeft"
shell:SystemTray.IsVisible="False">
 
<!--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 -->
<Canvas.Background>
<VideoBrush x:Name="viewfinderBrush" />
</Canvas.Background>
</Canvas>
</Grid>
 
</phone:PhoneApplicationPage>

Adding capabilities

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.

Camera initialization

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);
viewfinderBrush.SetSource(_cam);
}
}
}

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.

Adjusting the canvas size

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)
{
this.Dispatcher.BeginInvoke(delegate()
{
_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.

Capturing image

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";
try
{
// Save photo to the media library camera roll.
_library.SavePictureToCameraRoll(fileName, e.ImageStream);
}
finally
{
// Close image stream
e.ImageStream.Close();
}
}

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.

Listening to shutter button event

We are almost done. To capture an image we need to call the method CaptureImage of PhotoCamera. To do that let's listen to the cellphone button designed for the camera, which is the shutter button. Listen this button event is quite easy. Just add the following line to the OnNavigatedTo method:

CameraButtons.ShutterKeyPressed += OnButtonFullPress;

and add the onButtonFullPress method:

private void OnButtonFullPress(object sender, EventArgs e)
{
if (_cam != null)
{
_cam.CaptureImage();
}
}

Conclusion

With this simple code we can get the Windows Phone camera working quickly. In order to maintain simplicity it didn't show advanced resources such as flash, focus and lenses, but you can learn how to use these resources here.

Source Code

You can download the source code here: File:CameraApp.zip

Reference

This page was last modified on 4 July 2013, at 08:28.
310 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.

×