Introducing Windows Phone 7 Photo Features (part 1) - Using a Chooser to Take Photos

6/7/2011 11:44:05 AM
Before we delve into developing a Windows Phone 7 application that snaps photos and manipulates them, it's important to understand the model for working with photos on this device. Each application deployed to the device runs in its own sandbox, or execution environment. This execution sandbox prevents third-party applications from directly accessing common data stores on the phone, such as photos or contact lists, and prevents them from directly invoking the applications that ship with a Windows Phone device, such as the camera or a messaging application. So how can you build an application that can take pictures, manipulate them, and save them to the phone? The answer is through launchers and choosers as shown in Table 1 and 2.
Table 1. Launchers
EmailComposeTaskOpens the default device e-mail composer.
MarketPlaceDetailTaskOpens detailed product information.
MarketPlaceDetailTaskOpens to the Marketplace with specified category.
MarketPlaceReviewTaskOpens the product review for the specified product.
MarketPlaceSearchTaskOpens the MarketPlace search result based on the search term specified.
MediaPlayerLauncherOpens the default device MediaPlayer.
PhoneCallTaskOpens the Phone application with specified number ready to dial.
SearchTaskOpens the default search application.
SmsComposeTaskOpens the messaging application.
WebBrowserTaskOpens the default device web browser to the specified URL.

Table 2. Choosers
CameraCaptureTaskOpens the Camera application to capture the image.
EmailAddressChooserTaskOpens the Contact application to choose an e-mail.
PhoneNumberChooserTaskOpens the Phone application to choose a phone number.
PhotoChooserTaskOpens the Photo Picker application to choose the image.
SaveEmailAddressTaskSaves the provided e-mail to the Contact list.
SavePhoneNumberTaskSaves the phone number to the Contact list.

The Windows Phone Launchers and Choosers framework is a collection of APIs you can use to indirectly access core Windows Phone applications, like the phone or contact list, to perform a specific task. Launchers can launch a phone application but return no data. A chooser, such as a photo chooser, on the other hand, returns data to the application that calls it. Tables 16-1 and 16-2 list all of the launchers and choosers that ship with the Windows Phone platform today and how each is used. The CameraCaptureTask chooser launches the built-in Windows Phone camera application, allowing a user of a third-party application to snap photos and for the application to retrieve them for its own purposes by handling the chooser's Completed event. You will write code to capture photos shortly, but before you do that, it's important to understand one more basic concept when working with launchers and choosers—the application execution model and application tombstoning .

As you know by now, the first version of the Windows Phone 7 platform does not support multitasking due to the excessive demands it puts on the battery and other resources on the device. Launchers and choosers are, in essence, separate applications that are launched from within your application. Since support for multitasking does not exist, your application effectively terminates when launchers or choosers are used. This termination is known as tombstoning, and it has direct implications on programming Windows Phone 7 devices that use launchers and choosers. The difference between application tombstoning and application termination is that when an application is tombstoned, it is fully expected to be resumed upon completion of the launcher or chooser. Upon resuming, the application should continue in the same state that it was left off in, with data specific to the application session before tombstoning properly preserved. It is up to the application programmer to ensure that happens and that data gets properly restored.

1. Using a Chooser to Take Photos

The very first application that you will write will take photos and bring them inside your application. You will, therefore, create a basic navigation system in this first step for your application using an Application Bar and a standard set of icons that ship with Microsoft Expression for Windows Phone. You'll find the icons for a 32-bit system at C:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Icons, or for a 64-bit system at C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.0\Icons.

You will use choosers to implement photo manipulation features on Windows Phone 7. To take photos, you will use the CameraCaptureTask chooser to take the photo and bring that photo inside your application. Follow this walkthrough to accomplish these tasks.

1.1. Creating a New Project and Building the User Interface

In the first part of the walkthrough, you will create a new project and add necessary user interface elements to allow photo manipulation.

  1. Launch Visual Studio 2010 Express for Windows Phone, and create a new Windows Phone Application project. Name it "PhotoCapture."

You will create an Application Bar with three icons. The first button of the Application Bar will be for taking photos, which is the subject of the current walkthrough. The second button will be for opening previously taken photos. Finally, the third button will be for saving photos to the phone.

  1. Create a separate folder within your application to store Application Bar icons. To do that, right-click the name of the project within Solution Explorer, choose Add => New Folder, and name that folder images.

  2. You will use the standard Application Bar icons that came pre-installed with Microsoft Expression Blend for Windows Phone. By default, the icons are installed in the C:\Program Files\Microsoft SDKs\Windows phone\v7.0\Icons folder. Within that folder, go to the subfolder called dark, and, using Windows Explorer, copy the following icons into the images folder within your application:,, and

  3. Now you need to make the icons part of your solution. Highlight all three icons, and press F4 to bring up the Properties dialog. For the Build Action property, specify Content. Then, select Copy Always for the Copy to Output Directory property.

  4. With icons ready for use in the Application Bar, you are ready to add an Application Bar to MainPage.xaml (for an in-depth explanation of how to add and use an Application Bar within your application). Open MainPage.xaml, and paste the following code at the end of the XAML file just before the </phone:PhoneApplicationPage> closing tag. This XAML replaces the auto-generated template for the Application Bar:

    <shell:ApplicationBar IsVisible="True">
    <shell:ApplicationBarIconButton x:Name="btnCamera" Text="Take Photo" IconUri="images/" Click="btnCamera_Click"/>
    <shell:ApplicationBarIconButton Text="Open Photo" IconUri="images/"/>
    <shell:ApplicationBarIconButton Text="Save Photo" IconUri="images/"/>


    The btnCamera_Click event handler will be called when the user clicks the Take Photo button. You will write code for this event handler in the next section.

  5. Finally, you need to add an Image control to show the photos taken within your application. From the Toolbox, drag and drop an Image control onto the MainPage.xaml design surface, place it in the middle, and size it to be about half of the available screen space. Name it imgPhoto.

1.2. Writing Code to Take Photos with CameraCaptureTask

Although we may lose a bit of flexibility when programming with launchers and choosers, it is hard to dispute how easy they have made working with common phone tasks, such as taking pictures. In the following steps, you will launch a PhotoCapture application and wire up a callback event to invoke when that application completes.

  1. Open MainPage.xaml.cs (right-click MainPage.xaml and select View Code). Add the following using statements to the very top of the code page:

    using Microsoft.Phone.Tasks;
    using Microsoft.Phone;

  2. Add the following class-level variables within the MainPage class (right above the MainPage constructor):

    private CameraCaptureTask cameraCaptureTask;
    byte[] imageBits;

  3. Add the following code for the btnCamera_Click method. This will invoke the PhotoCapture application when the user clicks the first button in the Application Bar:

    private void btnCamera_Click(object sender, EventArgs e)

You are now ready to write event handler code that will be invoked when the CameraCaptureTask chooser completes its work (the user has taken a picture) and control returns to your application. When control returns to your application, the photo taken by the user is passed in as one of the arguments to the callback function; you will take that photo and show it in the imgPhoto image control that you have added previously. Add the following method, which will be executed when the chooser completes, to MainPage.xaml.cs.

private void PhotoChooserTaskCompleted(object sender, PhotoResult e)
if (e.ChosenPhoto != null)
imageBits = new byte[(int)e.ChosenPhoto.Length];
e.ChosenPhoto.Read(imageBits, 0, imageBits.Length);
e.ChosenPhoto.Seek(0, System.IO.SeekOrigin.Begin);

var bitmapImage = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
this.imgPhoto.Source = bitmapImage;

  1. You need to tell your application's instance of CameraCaptureTask that the PhotoChooserTaskCompleted method must be invoked upon its completion. You will do this within the MainPage() constructor using the following two lines of code:

    cameraCaptureTask = new CameraCaptureTask();
    cameraCaptureTask.Completed += PhotoChooserTaskCompleted;

You are now ready to run the application. Note that for this walkthrough, it is not completely necessary to deploy your application to the physical device, since the emulator provides limited simulated photo-taking capabilities.

  1. Press F5 to run the application on the emulator, and then press the camera button in the Application Bar to be presented with the Windows Phone 7 PhotoCapture application. Press the button in the upper right-hand corner to simulate photo-taking within the emulator (notice how this simulation consists of a black rectangle moving around the screen's perimeter), and then press the Accept button to accept the photo—you should see a phone screen similar to the one shown in Figure 16-1, with your application displaying the captured image. Of course, if you deploy this application to the actual Windows Phone 7 device, the photos look a bit more exciting.

Throughout the rest of this article, you will continue enhancing this application by wiring the rest of the Application Bar icons, getting familiar with the Model-View-ViewModel pattern, as well as integrating your application within the Windows Phone 7 experience, including handy image uploads to Twitter.

Figure 1. Results of PhotoCapture on Windows Phone 7 emulator
  •  Mobile Application Security : Bluetooth Security - Bluetooth Technical Architecture
  •  Mobile Application Security : Bluetooth Security - Overview of the Technology
  •  Windows Phone 7 Development : Push Notifications - Implementing Cloud Service to Track Push Notifications
  •  Windows Phone 7 Development : Push Notifications - Implementing Raw Notifications
  •  Windows Phone 7 Development : Push Notifications - Implementing Tile Notifications
  •  Windows Phone 7 Development : Push Notifications - Implementing Toast Notifications
  •  iPhone Application Development : Creating a Navigation-Based Application
  •  Windows Phone 7 Development : Push Notifications - Introducing the Push Notifications Architecture
  •  Windows Phone 7 Development : Push Notifications - Understanding Push Notifications
  •  Windows Phone 7 Development : Handling Multiple Concurrent Requests with Rx.NET
  •  WAP and Mobile HTML Security : Application Attacks on Mobile HTML Sites
  •  WAP and Mobile HTML Security : Authentication on WAP/Mobile HTML Sites & Encryption
  •  iPhone Application Development : Displaying and Navigating Data Using Table Views - Building a Simple Table View Application
  •  iPhone Application Development : Understanding Table Views and Navigation Controllers
  •  Windows Phone 7 Development : Revising WeatherRx to Manage Slow Data Connections
  •  Windows Phone 7 Development : Handling Data Connection Issues with Rx.NET
  •  Windows Phone 7 Development : Handling Errors in Rx.NET
  •  Windows Phone 7 Development : Using Rx.NET with Web Services to Asynchronously Retrieve Weather Data
  •  Windows Phone 7 Development : Media - Adding Sounds to an Application
  •  iPhone Application Development : Building a Multi-View Tab Bar Application (part 4) - Implementing the Summary View
    Top 10
    Nikon 1 J2 With Stylish Design And Dependable Image And Video Quality
    Canon Powershot D20 - Super-Durable Waterproof Camera
    Fujifilm Finepix F800EXR – Another Excellent EXR
    Sony NEX-6 – The Best Compact Camera
    Teufel Cubycon 2 – An Excellent All-In-One For Films
    Dell S2740L - A Beautifully Crafted 27-inch IPS Monitor
    Philips 55PFL6007T With Fantastic Picture Quality
    Philips Gioco 278G4 – An Excellent 27-inch Screen
    Sony VPL-HW50ES – Sony’s Best Home Cinema Projector
    Windows Vista : Installing and Running Applications - Launching Applications
    Most View
    Bamboo Splash - Powerful Specs And Friendly Interface
    Powered By Windows (Part 2) - Toshiba Satellite U840 Series, Philips E248C3 MODA Lightframe Monitor & HP Envy Spectre 14
    MSI X79A-GD65 8D - Power without the Cost
    Canon EOS M With Wonderful Touchscreen Interface (Part 1)
    Windows Server 2003 : Building an Active Directory Structure (part 1) - The First Domain
    Personalize Your iPhone Case
    Speed ​​up browsing with a faster DNS
    Using and Configuring Public Folder Sharing
    Extending the Real-Time Communications Functionality of Exchange Server 2007 : Installing OCS 2007 (part 1)
    Google, privacy & you (Part 1)
    iPhone Application Development : Making Multivalue Choices with Pickers - Understanding Pickers
    Microsoft Surface With Windows RT - Truly A Unique Tablet
    Network Configuration & Troubleshooting (Part 1)
    Panasonic Lumix GH3 – The Fastest Touchscreen-Camera (Part 2)
    Programming Microsoft SQL Server 2005 : FOR XML Commands (part 3) - OPENXML Enhancements in SQL Server 2005
    Exchange Server 2010 : Track Exchange Performance (part 2) - Test the Performance Limitations in a Lab
    Extra Network Hardware Round-Up (Part 2) - NAS Drives, Media Center Extenders & Games Consoles
    Windows Server 2003 : Planning a Host Name Resolution Strategy - Understanding Name Resolution Requirements
    Google’s Data Liberation Front (Part 2)
    Datacolor SpyderLensCal (Part 1)