Using the Camera in Windows Phone 7

Windows Phone From Scratch #24

On January 24 we created an application that launched the contact list and returned camera the phone number of the selected contact.  In that posting I reviewed, briefly, the difference between Launchers and Choosers. This posting builds on that work.

Today we will use the Chooser for the Camera, which will bring up the camera and then return the location of the image taken.

To begin, create a new Windows Phone application, called Camera Test.

On the main page place a Button and an Image control,

 <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        Height="101*" />
        Height="506*" />
     Width="160" />
     Width="303" />

Following the same pattern as we saw with the Contacts chooser, declare the camera chooser as a member variable of the class,

using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;

namespace CameraTest
   public partial class MainPage :
      CameraCaptureTask _cameraCapture =
          new CameraCaptureTask();

Wire up the click event handler to call Show on the CameraCaptureTask and wire up an event handler for the callback to handle the picture that was taken,

public MainPage()
   _cameraCapture.Completed +=
      new EventHandler<PhotoResult>(
         _cameraCapture_Completed );
   Photo.Click += new RoutedEventHandler(
      Photo_Click );

Finally, in the callback, you’ll obtain the fileName that contains the image and use that to create a new BitMapImage which can serve as the Source for your Image control,

void _cameraCapture_Completed(
   object sender, PhotoResult e )
   if ( e.TaskResult == TaskResult.OK )
      Image1.Source = new BitmapImage(
         new Uri( e.OriginalFileName ) );

The emulator provides a simulated image to capture (a small moving rectangle against a white background) and a simulated button to snap to capture the image when the rectangle is where you want it.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in Patterns & Skills, WindowsPhone and tagged , . Bookmark the permalink.

2 Responses to Using the Camera in Windows Phone 7

  1. Pingback: Tweets that mention Using the Camera in Windows Phone 7 | Jesse Liberty --

Comments are closed.