Working with CameraCaptureTask in Windows Phone

Working with Camera in Windows Phone environment is a common requirement. Almost 25% of the apps in the store uses Camera capture on the app. CameraCaptureTask is a common Task available to the Windows Phone device which can capture camera from an app by launching the basic image capture tool present on the Windows Phone environment and take a picture and give the bytes to you. Here is now you can implement it.

var cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += (s,e) => {
    if (e.TaskResult == TaskResult.OK)
    { 
         System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
        bmp.SetSource(e.ChosenPhoto);
        myImage.Source = bmp;
    }
};
cameraCaptureTask.Show();

The above code creates an object of CameraCaptureTask and invokes its Show method. The Show method will launch the Camera Task on the phone and when user captures the image, it will send the Image bytes to the Completed event. Inside the Completed event, we can have the Image stream available as e.ChosenPhoto. Here we simply displayed the stream in myImage control.

You can take the stream and do whatever you feel. For instance you can save the image in MediaLibrary using the following code.

byte[] ibytes = new byte[(int)e.ChosenPhoto.Length];
e.ChosenPhoto.Read(ibytes , 0, ibytes .Length);
e.ChosenPhoto.Seek(0, SeekOrigin.Begin);
MediaLibrary library = new MediaLibrary();
library.SavePicture("myPhoto.jpg", ibytes );

The above code will save the image as myphoto.jpg to the Picture library. You can also pass the image stream to a WriteableBitmap to modify the content.

 WriteableBitmap writeableBitmap = new WriteableBitmap(200, 200);
 writeableBitmap.LoadJpeg(e.ChosenPhoto);

I hope this will help you while dealing with Photo based applications in Windows Phone. Thanks for reading.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434