×
Namespaces

Variants
Actions
(Difference between revisions)

Minimal Camera app in Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search
diegodobelo (Talk | contribs)
(Diegodobelo -)
hamishwillee (Talk | contribs)
m (Hamishwillee -)
 
(15 intermediate revisions by 3 users not shown)
Line 1: Line 1:
[[Category:Draft]]
+
[[Category:Camera on Windows Phone]][[Category:Getting Started on Windows Phone‎]][[Category:Code Examples]][[Category:Windows Phone 8]]
''Delete instructional text in italic''
+
{{Abstract|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.
 
+
{{ArticleMetaData
{{Abstract|This article explains how to ... }} ''Replace the abstract text with a short paragraph (or sentence) describing what the topic covers.''
+
|sourcecode=[[file:CameraApp.zip]] <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
 
+
''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''
+
{{ArticleMetaData <!-- v1.3 -->
+
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
+
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.wgt]]) -->
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.wgt]]) -->
|devices= <!-- Devices tested against - e.g. Nokia Lumia 928, Nokia Asha 501) -->
+
|devices=Nokia Lumia 620
|sdk= <!-- SDK(s) built and tested against (e.g. Windows Phone 8.0 SDK) -->
+
|sdk= [http://dev.windowsphone.com/en-us/downloadsdk Windows Phone 8.0 SDK]
|platform= <!-- Compatible platforms - e.g. Nokia Asha Platform 1.0 and later -->
+
|platform= Windows Phone 8 and later
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->  
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
|signing=<!-- Special Signing requirements -->
+
|signing= <!-- Special Signing requirements -->
|capabilities= <!-- Required capabilities for code (e.g. ID_CAP_LOCATION, ID_CAP_NETWORKING) -->
+
|capabilities=ID_CAP_ISV_CAMERA, ID_CAP_MEDIALIB_PHOTO
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|translated-by= <!-- [[User:XXXX]] -->
 
|translated-by= <!-- [[User:XXXX]] -->
|translated-from-title= <!-- Title only - not link -->  
+
|translated-from-title= <!-- Title only - not link -->
 
|translated-from-id= <!-- Id of translated revision -->
 
|translated-from-id= <!-- Id of translated revision -->
|review-by=<!-- After re-review: [[User:username]] -->
+
|review-by= <!-- After re-review: [[User:username]] -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-timestamp= <!-- After significant update: YYYYMMDD -->
 
|update-timestamp= <!-- After significant update: YYYYMMDD -->
|creationdate= <!-- Format YYYYMMDD -->
+
|creationdate= 20130617
|author= <!-- Enter link [[User:username]] -->
+
|author= [[User:Diegodobelo]]
 
}}
 
}}
 
== Introduction ==
 
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.
 
  
 
== Setup ==
 
== Setup ==
Install the Windows Phone 8 SDK: http://dev.windowsphone.com/en-us/downloadsdk
+
# Install the [http://dev.windowsphone.com/en-us/downloadsdk Windows Phone 8 SDK]
 
+
# Open Visual Studio. Select '''File | New Project...'''
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'''.
  
On Templates section select Visual C #-> Windows Phone -> Windows Phone App
 
  
Enter the project name and press OK.
+
== The XAML ==
 
+
In the '''MainPage.xaml''' file update the element {{Icode|phone:PhoneApplicationPage}} to lock the orientation on landscape and to hide the system tray:
Select Windows Phone OS 8.0 as the target Windows Phone OS version and press OK.
+
 
+
== Implementation ==
+
In the ''MainPage.xaml'' file update the element phone:PhoneApplicationPage to lock the orientation on landscape and to hide the system tray:
+
  
 
<code xml>
 
<code xml>
Line 47: Line 37:
 
</code>
 
</code>
  
Now delete the <Grid.RowDefinitions> element and add the following canvas element:
+
Now delete the {{Icode|<Grid.RowDefinitions>}} element and add the following canvas element:
  
 
<code xml>
 
<code xml>
Line 58: Line 48:
 
</code>
 
</code>
  
Now the MainPage.xaml will look like:
+
Now the '''MainPage.xaml''' will look like:
  
 
<code xml>
 
<code xml>
Line 89: Line 79:
 
</code>
 
</code>
  
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.
+
== 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 {{Icode|ID_CAP_ISV_CAMERA}} and {{Icode|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:
+
== Camera initialization ==
 +
Open the '''MainPage.xaml.cs''' file and add the following directive at the top of the page:
  
 
<code csharp>
 
<code csharp>
Line 123: Line 115:
 
</code>
 
</code>
 
   
 
   
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'''.
+
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 {{Icode|viewfinderBrush}}, which was defined at the '''MainPage.xaml''' file as a {{Icode|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.
+
Note that the compiler is complaining about missing {{Icode|cam_Initialized}} and {{Icode|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:
+
== Adjusting the canvas size ==
 +
The camera image is shown into the canvas created in '''MainPage.xaml''' called {{Icode|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:
  
 
<code csharp>
 
<code csharp>
Line 134: Line 127:
 
</code>
 
</code>
  
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:
+
There are several devices with different screens and aspect ratios. There are also several camera resolutions. A good approach is to calculate the canvas {{Icode|width}} and {{Icode|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:
  
 
<code csharp>
 
<code csharp>
Line 151: Line 144:
 
It will get the available camera resolutions to calculate the aspect ratio.
 
It will get the available camera resolutions to calculate the aspect ratio.
  
Add the cam_Initialized method:
+
Add the {{Icode|cam_Initialized}} method:
  
 
<code csharp>
 
<code csharp>
Line 169: Line 162:
 
</code>
 
</code>
  
''Remove Category:Draft when the page is complete or near complete''
+
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 {{Icode|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:
 +
<code csharp>
 +
using Microsoft.Xna.Framework.Media;
 +
</code>
 +
 
 +
and add this attribute to the class:
 +
 
 +
<code csharp>
 +
private MediaLibrary _library = new MediaLibrary();
 +
</code>
 +
 
 +
This is the class that saves the image in camera roll. We will use it into {{Icode|cam_CaptureImageAvailable}} method:
 +
 
 +
<code csharp>
 +
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();
 +
    }
 +
}
 +
</code>
 +
 
 +
In this method we set up the {{Icode|fileName}} and then we call the method {{Icode|SavePictureToCameraRoll}} of {{Icode|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 {{Icode|OnNavigatedTo}} method:
 +
 
 +
<code csharp>
 +
CameraButtons.ShutterKeyPressed += OnButtonFullPress;
 +
</code>
 +
 
 +
and add the {{Icode|onButtonFullPress}} method:
 +
 
 +
<code csharp>
 +
private void OnButtonFullPress(object sender, EventArgs e)
 +
{
 +
    if (_cam != null)
 +
    {
 +
        _cam.CaptureImage();
 +
    }
 +
}
 +
</code>
  
 +
== 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 [http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202973(v=vs.105).aspx here].
  
''The "platform categories" will be displayed here in '''preview''' only - Copy paste relevant categories into text here''
+
== Source Code ==
 +
You can download the source code here: [[File:CameraApp.zip]]
  
''Add categories below using category selector. To see appropriate versions for each platform you can add the  <nowiki>{{</nowiki>VersionHint}} template and preview the page. Then copy-paste the ones you want.''
+
== Reference ==
 +
*[http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202973(v=vs.105).aspx Camera and photos for Windows Phone].

Latest revision as of 08:28, 4 July 2013

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

[edit] 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.


[edit] 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>

[edit] 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.

[edit] 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.

[edit] 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.

[edit] 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.

[edit] 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();
}
}

[edit] 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.

[edit] Source Code

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

[edit] Reference

This page was last modified on 4 July 2013, at 08:28.
316 page views in the last 30 days.
×