September 22, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Building a Windows Phone 8.0 Lens Application

  • April 1, 2013
  • By Vipul Patel
  • Send Email »
  • More Articles »

Introduction

With the release of Windows Phone 8, Microsoft has enabled application developers with the ability to build camera applications that can very tightly integrate with the built-in camera app. It also allows camera applications to offer a rich media experience for viewing the great photos one might have taken.

Such camera applications, which tightly integrate with the built-in camera applications are called “lens”. Lens offers customers the experience of using their camera differently, and optionally the ability to provide a viewing and editing experience different from the built-in type.

For example, a developer can build a lens application that can process bar codes.

To become a lens application, the Windows Phone application must provide a viewfinder capability via the camera's APIs.  This is needed as the application will work directly with the camera's APIs.

Let’s get our hands dirty with building our mock lens application.

Hands-On

Start Visual Studio 2012 and create a new Windows Phone application called WindowsPhoneLensDemo.

New Project: Windows Phone App
New Project: Windows Phone App

When prompted, select Windows Phone OS 8.0 as the target Windows Phone platform for the application.

Target Windows Phone OS Version: Windows Phone OS 8.0
Target Windows Phone OS Version: Windows Phone OS 8.0

Since our application will need to work with the camera and the photo library, we need to declare the capabilities, else our application will crash when these features are invoked from our application. Open WMAppManifest.xml and select ID_CAP_ISV_CAMERA and ID_CAP_MEDIALIB_PHOTO as the capabilities of the application.

Select ID_CAP_ISV_CAMERA and ID_CAP_MEDIALIB_PHOTO as the capabilities of the application
Select ID_CAP_ISV_CAMERA and ID_CAP_MEDIALIB_PHOTO as the capabilities of the application

As part of building the application, we need to provide the application with 3 icons for our lens application. These icons will be rendered when a user clicks on the lens icon in the built-in camera application.

These icon template files are available at http://go.microsoft.com/fwlink/?LinkId=266547

The lens icons will have the following dimensions.

Resolution

Icon size

File Name

WXGA

277 x 277 pixels

Lens.Screen-WXGA.png

HD720p

259 x 259 pixels

Lens.Screen-720p.png

WVGA

173 x 173 pixels

Lens.Screen-WVGA.png

We need to add these icons under the assets folder in the project. Once you have added these files, they will look like the screenshot below.

Add the icons under the assets folder in the project
Add the icons under the assets folder in the project

Note that the dimensions and the names of the files have to match, else the application will not work properly.

Next, we will build support for integrating our application as a lens by declaring it as a Camera_Capture_App extension.

An extension is declared below:

    <Extensions>

      <Extension ExtensionName ="Camera_Capture_App" 

           ConsumerID="{5B04B775-356B-4AA0-AAF8-6491FFEA5631}"

           TaskID="_default" />

    </Extensions>

Add the highlighted blurb in our application manifest file.

// WMAppManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0">

  <DefaultLanguage xmlns="" code="en-US" />

  <App xmlns="" ProductID="{9921c193-6355-4469-84ac-70c5d27a63fa}" Title="WindowsPhoneLensDemo" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" Author="WindowsPhoneLensDemo author" Description="Sample description" Publisher="WindowsPhoneLensDemo" PublisherID="{c53122e6-b21b-4661-a7d3-c222392d1289}">

    <IconPath IsRelative="true" IsResource="false">Assets\ApplicationIcon.png</IconPath>

    <Capabilities>

      <Capability Name="ID_CAP_NETWORKING" />

      <Capability Name="ID_CAP_MEDIALIB_AUDIO" />

      <Capability Name="ID_CAP_MEDIALIB_PLAYBACK" />

      <Capability Name="ID_CAP_SENSORS" />

      <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />

      <Capability Name="ID_CAP_ISV_CAMERA" />

      <Capability Name="ID_CAP_MEDIALIB_PHOTO" />

    </Capabilities>

    <Tasks>

      <DefaultTask Name="_default" NavigationPage="MainPage.xaml" />

    </Tasks>

    <Tokens>

      <PrimaryToken TokenID="WindowsPhoneLensDemoToken" TaskName="_default">

        <TemplateFlip>

          <SmallImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileSmall.png</SmallImageURI>

          <Count>0</Count>

          <BackgroundImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileMedium.png</BackgroundImageURI>

          <Title>WindowsPhoneLensDemo</Title>

          <BackContent>

          </BackContent>

          <BackBackgroundImageURI>

          </BackBackgroundImageURI>

          <BackTitle>

          </BackTitle>

          <DeviceLockImageURI>

          </DeviceLockImageURI>

          <HasLarge>

          </HasLarge>

        </TemplateFlip>

      </PrimaryToken>

    </Tokens>

    <Extensions>

      <Extension ExtensionName ="Camera_Capture_App" 

           ConsumerID="{5B04B775-356B-4AA0-AAF8-6491FFEA5631}"

           TaskID="_default" />

    </Extensions>

    <ScreenResolutions>

      <ScreenResolution Name="ID_RESOLUTION_WVGA" />

      <ScreenResolution Name="ID_RESOLUTION_WXGA" />

      <ScreenResolution Name="ID_RESOLUTION_HD720P" />

    </ScreenResolutions>

  </App>

</Deployment>

Add a button at the bottom of our home page, and call it Click.

Now, in the MainPage.xaml, add the following using statements to include the namespaces, which are needed to work with the camera and the media library.

using Microsoft.Devices;

using Microsoft.Xna.Framework.Media;

Next, in MainPage.xaml, we add the code to add a canvas, which will render the viewfinder. For that, we will need to add a Canvas object in the Grid Object.

Add the highlighted code.

<Grid x:Name="LayoutRoot" Background="Transparent">

        <Grid.RowDefinitions>

            <RowDefinition Height="Auto"/>

            <RowDefinition Height="*"/>

        </Grid.RowDefinitions>

 

        <!-- LOCALIZATION NOTE:

            To localize the displayed strings copy their values to appropriately named

            keys in the app's neutral language resource file (AppResources.resx) then

            replace the hard-coded text value between the attributes' quotation marks

            with the binding clause whose path points to that string name.

 

            For example:

 

                Text="{Binding Path=LocalizedResources.ApplicationTitle, Source={StaticResource LocalizedStrings}}"

 

            This binding points to the template's string resource named "ApplicationTitle".

 

            Adding supported languages in the Project Properties tab will create a

            new resx file per language that can carry the translated values of your

            UI strings. The binding in these examples will cause the value of the

            attributes to be drawn from the .resx file that matches the

            CurrentUICulture of the app at run time.

         -->

 

        <!--TitlePanel contains the name of the application and page title-->

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">

            <TextBlock Text="LENS DEMO" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>

            <TextBlock Text="My Lens Main Page" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>

            

        </StackPanel>

 

        <!--ContentPanel - place additional content here-->

        <Grid x:Name="ContentPanel" Background="Transparent">

            <Grid.RowDefinitions>

                <RowDefinition Height="100"/>

                <RowDefinition Height="*"/>

            </Grid.RowDefinitions>

 

            <Canvas x:Name="canvasCameraView"   Width="480" Height="640"

                   HorizontalAlignment="Stretch" VerticalAlignment="Bottom" >

 

                <!--Camera viewfinder -->

                <Canvas.Background>

                    <VideoBrush x:Name="viewfinderBrush" />

                </Canvas.Background>

            </Canvas>

 

        </Grid>

In the code snippet above, we have added a canvas called canvasCameraView and set the background of the Canvas as a videobrush.

We next proceed to add a PhotoCamera object and a MediaLibrary object to our class, and a variable, which we will use later to name our photos.

We will declare these in the MainPage class.

public partial class MainPage : PhoneApplicationPage

    {

        PhotoCamera myCamera;

        MediaLibrary mediaLibrary;

        int startVal = 0;

        // Constructor

In the constructor, we will initialize the media library and start the primary camera and wire up the CaptureImageAvailable event.

public MainPage()

        {

            InitializeComponent();

            mediaLibrary = new MediaLibrary();

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

            

            myCamera.CaptureImageAvailable += myCamera_CaptureImageAvailable;

 

            viewfinderBrush.SetSource(myCamera);

 

            // Sample code to localize the ApplicationBar

            //BuildLocalizedApplicationBar();

        }

Next, we will add the implementation of the PhotoCamera’s CaptureImageAvailable event.

void myCamera_CaptureImageAvailable(object sender, ContentReadyEventArgs e)

        {

            startVal++;

            string filename = startVal.ToString();

            mediaLibrary.SavePictureToCameraRoll(filename, e.ImageStream);

 

        }

Finally, we will implement the click event for the Button, which is titled “Click”.

This method will call the camera APIs to capture the image.

private void Button_Click_1(object sender, RoutedEventArgs e)

        {

            if (myCamera != null)

                myCamera.CaptureImage();

        }

Our implementation of a very basic lens application is now complete. If you have trouble following along, you can download a copy of the sample code below.

Now, build and start the application.

When the application starts, the camera will start. So, if you are working with the emulator, you need to exit the lens application and go back to the home screen and start the Camera application from the application list.

Home screen
Home screen

On the Camera application, click on left-most icon on the bottom, which is the icon for the lenses.

Click on left-most icon on the bottom
Click on left-most icon on the bottom

This will navigate the camera application to a page that lists all the available lenses on the device.

You will notice that our lens application is visible in the list. Click on your lens icon (this is the same icon we added to the project under the Assets folder).

Our lens application is visible in the list
Our lens application is visible in the list

In our application, you can see that the viewfinder is at the very top of the screen.

Click on the lens icon
Click on the lens icon

When you click on the button titled “Click”, it will take pictures. Even on the emulator, you can take dummy pictures.

To verify that our application actually took pictures, you can navigate to the Photos application and click on the Camera Roll and see the pictures that our application has taken.

You have now successfully built a windows Phone lens application. This application only provides basic functionality to capture what is visible to the camera. Windows Phone developers are encouraged to use the knowledge acquired in this article to build exciting lens applications.

Summary

In this article, we walked through building a lens application for Windows Phone 8.0. I hope you have found this information useful.

WindowsPhoneLensDemo

About the author

Vipul Patel is a Program Manager currently working at Amazon Corporation. He has formerly worked at Microsoft in the Lync team and in the .NET team (in the Base Class libraries and the Debugging and Profiling team). He can be reached at vipul.patel@hotmail.com


Tags: application, camera, lens, Windows Phone 8




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel