Writing a Windows Phone 7.5 Camera Application

Overview

Windows Phone Mango, the latest released version of the Windows Phone operating system now allows access to the camera programmatically. This means that application developers can now leverage the built-in camera on these devices in their applications. In this article, we will walk through how to build a simple Windows Phone Mango Camera application.

Camera Basics

To start with, we need to understand a few camera basics on Windows Phone devices.

  • You can build a camera application that can capture still photos.
  • You can query device camera capabilities (where there are multiple cameras on the device (front and/or rear), where it has flash, etc.).
  • You can get raw camera frames and process them yourself (encode/decode).
  • You can programmatically set flash and focus when taking a photo.
  • You can change the resolution of the photo.
  • You can continue using the hardware button for the camera shutter to capture a photo and for auto-focus when taking shots outside your application.
  • A camera need not be present (for example, front facing camera was not a part of the original devices). Your application would need to handle that condition gracefully.
  • To allow your application to have access to the camera capability, you need to specify ID_CAP_ISV_CAMERA in your application manifest file.
  • To allow your application to have access to a front facing camera (if one exists), you need to specify ID_HW_FRONTCAMERA in your application manifest file.

Besides the camera APIs, you also have access to other Windows Phone APIs, which would allow an application to save captured photos into the media library, and to extend the built-in photo application and Pictures Hub.

Hands-On

We will now create a Windows Phone camera application. Fire off Visual Studio and create a new Windows Phone application project titled WPCameraDemo.

Create a new Windows Phone application project
Figure 1: Create a new Windows Phone application project

When prompted to select the target Windows Phone OS version, select Windows Phone OS 7.1 as shown below.

Select the target Windows Phone OS version
Figure 2: Select the target Windows Phone OS version

Add reference to Microsoft.Xna.Framework from the list of available components in the Add Reference Dialog.

Add reference to Microsoft.Xna.Framework
Figure 3: Add reference to Microsoft.Xna.Framework

Add a couple of buttons on the MainPage called Start and Click.

Also, add a Canvas titled CameraView, which will represent the ViewFinder screen in our application.

The XAML:

<Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
 
        <Canvas x:Name="canvasCameraView" Width="480" Height="640"
                   HorizontalAlignment="Stretch" >
 
            <!--Camera viewfinder -->
            <Canvas.Background>
                <VideoBrush x:Name="viewfinderBrush" />
            </Canvas.Background>
        </Canvas>
 
        <StackPanel Grid.Row="0" Margin="0">
            <Button x:Name="buttonStartCamera" Content="Start Camera" />
            <Button x:Name="buttonClickCamera" Content="Click" />
            
        </StackPanel>
 
        
    </Grid>

Note that we will add click events for the buttons later on in the exercise.

In the code-behind file for MainPage (MainPage.xaml.cs), add the following using statements, which we would need to access, to create variables.

using Microsoft.Devices;
using Microsoft.Xna.Framework.Media;

Now, add variables for a camera and Media Library in the MainPage.xaml.cs.

public partial class MainPage : PhoneApplicationPage
    {
        PhotoCamera myCamera;
 MediaLibrary mediaLibrary;
       

In the constructors of the MainPage, instantiate the mediaLibrary object.

public MainPage()
        {
            InitializeComponent();
            mediaLibrary = new MediaLibrary();
 
 
        }

Now, we will add code for the click events for the buttons we added above.

Double click the "Start Camera" button and add the following code to the event handler generated.

private void buttonStartCamera_Click(object sender, RoutedEventArgs e)
        {
            myCamera = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
 
            myCamera.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(camera_CaptureCompleted);
 
            myCamera.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(camera_CaptureImageAvailable); 
 
            viewfinderBrush.SetSource(myCamera);
 
        }

Here is what we did. The following line instantiated the camera.

myCamera = new Microsoft.Devices.PhotoCamera(CameraType.Primary);

We then added event handlers for the events of interest on the camera, namely, Capture completed and Capture image available.

            myCamera.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(camera_CaptureCompleted);
 
            myCamera.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(camera_CaptureImageAvailable); 

Lastly, we see the viewfinder source to the camera. This will allow us to see what the camera is seeing when we start the camera.

viewfinderBrush.SetSource(myCamera);

Now, we will go ahead and implement the Capture button click event.

private void buttonClickCamera_Click(object sender, RoutedEventArgs e)
        {
            if (myCamera != null)
                myCamera.CaptureImage();
        }

The above function is self-explanatory. We just ask the camera object to capture the image if it is instantiated.

Now, if you attempt to compile your code at this point, you will get errors because the camera_CaptureCompleted and camera_CaptureImageAvailable methods are not present.

We can use the Camera_CaptureCompleted event handler to update the status of our photo shoot event. It is helpful to the user to know whether he/she clicked the shoot button successfully or not.

Add a textbox on the Page called textBoxStatus and update the text on the textbox to show that the capture was completed.

void camera_CaptureCompleted(object sender, CameraOperationCompletedEventArgs e)
        {
            Thread.Sleep(100);
            Deployment.Current.Dispatcher.BeginInvoke(delegate()
            {
                textBoxStatus.Text = "Capture Completed";
 
            });
        }

We need to populate the image into the media library. We will use the CaptureImageAvailable event handler for this.

        void camera_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
        {
            startVal++;
            string filename = startVal.ToString();
            mediaLibrary.SavePictureToCameraRoll(filename, e.ImageStream);
            
            Deployment.Current.Dispatcher.BeginInvoke(delegate()
            {
                textBoxStatus.Text = "Image saved to Library";
            });
   
        }
 

Now we can compile and execute our first Windows Phone Camera application.

Note that in the emulator, there is no support for a virtual camera (the application will execute but you can't see anything) so you are better off trying this on your Windows Phone.

If you are having issues following along, you can download the sample code for the exercise below.

Summary

In this article, we learned the basics about Windows Phone camera and how to create a Windows Phone application, which utilizes the camera through APIs. I hope you have found this information useful.



About the Author

Vipul Vipul Patel

Vipul Patel is a Software Engineer currently working at Microsoft Corporation, working in the Office Communications Group and has worked in the .NET team earlier in the Base Class libraries and the Debugging and Profiling team. He can be reached at vipul_d_patel@hotmail.com

Related Articles

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: May 7, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT This eSeminar will explore three popular games engines and how they empower developers to create exciting, graphically rich, and high-performance games for Android® on Intel® Architecture. Join us for a deep dive as experts describe the features, tools, and common challenges using Marmalade, App Game Kit, and Havok game engines, as well as a discussion of the pros and cons of each engine and how they fit into your development …

  • Instead of only managing projects organizations do need to manage value! "Doing the right things" and "doing things right" are the essential ingredients for successful software and systems delivery. Unfortunately, with distributed delivery spanning multiple disciplines, geographies and time zones, many organizations struggle with teams working in silos, broken lines of communication, lack of collaboration, inadequate traceability, and poor project visibility. This often results in organizations "doing the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds