DotNetCurry Logo

Building an Image Transformation Application for Windows Phone 8

Posted by: Vikram Pendse , on 8/13/2014, in Category Windows Phone
Views: 10376
Abstract: Nokia Imaging SDK provides a simple and easy way to implement APIs making it easier for developers to use the SDK in their apps. In this article, we will build a Windows Phone 8 Image filtering application which will allows us to apply various filters and effects to our Images and also enables us to save and share them on Social platform.

The mobile phone industry is highly competitive. Microsoft realizes this and has been taking huge initiatives to improve the User and Developer experience for the Windows Phone Platform. The acquisition of Nokia Devices and Services business is a part of this initiative. Nokia continues to capture the Windows Phone market like no other OEM’s and continues to deliver excellent devices and a rich phone development platform.

Nokia has an edge over other Mobile vendors in their rich set of API’s and the documentation that comes along with it. Nokia Imaging SDK is one of these platforms that developers can leverage to deliver some cool imaging experiences to consumers. Other popular API’s by Nokia are the HERE Maps and Nokia MixRadio.

This article is published from the DotNetCurry .NET Magazine – A Free High Quality Digital Magazine for .NET professionals published once every two months. Subscribe to this eMagazine for Free and get access to hundreds of free tutorials from experts

In this article, we will make use of the Imaging SDK and build an Image filtering application which will allows us to apply various filters and effects to our Images and also enables us to save and share them on Social platform.

What is Nokia Imaging SDK?

Nokia Imaging SDK consists of APIs which allows developers to apply various filters and effects to images either taken from the Camera or on images which already exists on the phone. This SDK also allows advance image operations like Lens Blur, Cropping etc. and allows you to incorporate your own custom filters as well. In this article we are using Nokia Imaging SDK 1.1. Recently Nokia also announced version 1.2 but since it is still in Beta, we have focused on SDK 1.1.

Creating a new Windows Phone 8.0 Application

We will be building an application for the Windows Phone 8.0 Platform. Use a New Windows Phone Blank Project in Visual Studio 2013, to start with

create-new-phone-app

We are referring this application by the name “ImageFilta”, so you may see “ImageFilta” used throughout the article.

Note : If you use this application directly in Windows Phone 8.0 then it works as-is. You may have to change code in case if you choose Windows Phone 8.1 Blank App (Silverlight) Project Template. For Windows Phone 8.1 Blank App, which is WINRT based template, most of the code blocks will not work. So it is highly recommended that you rewrite this application in Windows Phone 8.1 if you are planning to migrate.

Install Nokia Imaging SDK version 1.1

To download the Nokia Imaging SDK from Visual Studio 2013, you can go to your NuGet package manager or package manager console and install the APIs as shown below

nokia-imaging-sdk

OR

console-nuget-package

The URL to download Nokia Imaging SDK is http://www.nuget.org/packages/NokiaImagingSDK/1.1.177

Once you install the package, you just need to use the libraries and start using the APIs. There are no registration or key or configuration settings like we have in the case of Maps application. However it is very important to note that while building app using Nokia Imaging SDK, you need to explicitly delete the “Any CPU” from Configuration Manager dialog in Visual Studio > Active Solution Platform and Keep x86. If you do not delete “Any CPU”, exception will be thrown while you execute your application.

Note: If you are interested to read more about Any CPU, Rick Byers offers a good explanation on why AnyCPU are usually more trouble than they're worth.

Building UI for ImageFilta

What we are looking to build is a page with various filters and options. There is a ScrollViewer at the bottom which will allow us to scroll across filters. This ScrollViewer contains a set of Image Controls. When a user taps the image, we will render a filtered image above it and perform operations like Save or Share from the AppBar at Bottom. This is how the UI will look like

apply-filters

Here is the XAML for above UI








    
    




    







    
        

    
    


    
    


    
    


    
    


    
    


    
    


    
    


    
    


    
    


    





XAML for App Bar :









    
        
        
    




Now let’s talk about each functionality one by one. Before that let’s get familiar with AppBar options here

application-bar

As you can see from the AppBar, there are four Primary options:

1. Load Image from Existing Storage(Phone/Albums)

2. Capture Live image from Camera

3. Save Image after applying specific filter to JPEG format

4. Share Image on Socials available on phone.

Now let’s get into more details for each functionality.

Load Image from Existing Storage

In this option, we will look at the approach to select an Image from the existing Albums on the Phone. For this purpose, we will make use of the PhotoChooserTask. Once you click on the “Open” icon in the AppBar, it will redirect you to Photos/Albums section on the phone.

// check namespace used from the code download

#region Global Variables
private string _fileName = string.Empty;
private String filtername = string.Empty;
private StreamImageSource source;
#endregion

private void mnuOpen_Click(object sender, EventArgs e)
{
     PhotoChooserTask chooser = new PhotoChooserTask();
     chooser.Completed += SelectImage;
     chooser.Show();
}

We are using the PhotoChooserTask which comes out of the box in Windows Phone 8.0 SDK. It allows us to navigate through albums and select individual images. You can see that we have attached a method “SelectImage” to chooser.Completed event. We will look at the “SelectImage” method shortly after looking at the approach of fetching live images from Camera.

Taking Live Images from the Camera

To capture live image from the Camera, we will use CameraCaptureTask available in Windows Phone 8.0 SDK out of the box. CameraCaptureTask will also allow us to accept or reject any image taken from the Camera as shown here:

camera-capture

private void mnuCamera_Click(object sender, EventArgs e)
{
     CameraCaptureTask cmrcapture = new CameraCaptureTask();
     cmrcapture.Completed += SelectImage;
     cmrcapture.Show();
}

Now let’s talk about SelectImage which is a common method for both the existing images and live images options. The SelectImage method allows you to apply filter on the fly to the selected image, either from Album or from Camera.

private async void SelectImage(object sender, PhotoResult e)
{
    if (e.TaskResult != TaskResult.OK || e.ChosenPhoto == null)
    {
        MessageBox.Show("Invalid Operation");
        return;
    }

    try
    {
        stkfilters.Visibility = System.Windows.Visibility.Visible;

        source = new StreamImageSource(e.ChosenPhoto);                

        // Antique Filter
        using (var antiqufilters = new FilterEffect(source))
        {                    
            var antique = new AntiqueFilter();
            antiqufilters.Filters = new IFilter[] { antique };
           
            var target = new WriteableBitmap((int)Img1.ActualWidth, (int)Img1.ActualHeight);

            using (var renderer = new WriteableBitmapRenderer(antiqufilters, target))
            {                       
                await renderer.RenderAsync();
                Img1.Source = target;
            }
        }

        //Flip Filter
        using (var flipfilters = new FilterEffect(source))
        {                   
            var flip = new FlipFilter(FlipMode.Horizontal);                   
            flipfilters.Filters = new IFilter[] { flip };

            var target = new WriteableBitmap((int)Img2.ActualWidth, (int)Img2.ActualHeight);

            using (var renderer = new WriteableBitmapRenderer(flipfilters, target))
            {
                await renderer.RenderAsync();
                Img2.Source = target;
            }
        }

        //Wrap Filter
        ...

        //Sketch Filter
        ...

        //Sepia Filter
        ...

        //MagicPen Filter
        ...

        //Solarize Filter
        ...

        //Negative Filter
        ...

        //Temparature and Tint Filter
        ...

        //Stamp Filter
        ...
    }

    catch (Exception exception)
    {
        MessageBox.Show("Some error occured, Please share feedback from Send Feedback Menu" + exception.Message.ToString());
        return;
    }
}

You can see that “SelectImage” takes PhotoResult as a parameter. Since we are taking an image from the Camera as well, it is recommended to use StreamImageSource. We are applying filters to individual images at the bottom, which shows the preview of the filter. We are also sending a couple of parameters to the filters like for StampFilter, TemperatureAndTintFilter etc. To know more about an individual Filter, you can visit the Nokia Imaging SDK API Documentation at

http://developer.nokia.com/resources/library/Imaging_API_Ref/nokiagraphicsimaging-namespace.html

You can see how these filters get applied to the individual images as shown here

filters-bottom-bar

To see a larger view of the image, click on the individual image containing that filter effect:

apply-filters

This can be achieved by tapping on each image as shown in the code here:

private void ApplyToOriginal(Image img)
{
   imgOrigin.Source = img.Source;           
}

private void Img1_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
       ApplyToOriginal(Img1);
       filtername = "Antique";
}

private void Img2_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
       ApplyToOriginal(Img2);
       filtername = "Flip";
}

Similarly you can follow the same procedure for the rest of the eight Images. After applying filters, we need to save our modified image to thePhone. For this, we will write a helper class “SaveImageHelper.cs”

Saving Image with Filter effect to the Phone

To save an image, we are assigning Filtername to each image in the ScrollViewer where we can see a list of images having the filter effects. So as discussed earlier, we will pass the filtername as a parameter along with filter and Image to the method in “SaveImageHelper.cs”. We have taken a simple Switch..Case here since we have limited number of filters. For our application we are not following any structure design pattern but you can always leverage some design patterns like MVVM.

private void mnuSave_Click(object sender, EventArgs e)
{
    SaveImageHelper smhelp = new SaveImageHelper();
    try
    {
        switch (filtername)
        {
            case "Antique": AntiqueFilter ant = new AntiqueFilter();
                smhelp.SaveImage(source, Img1, _fileName, ant);            
                break;

            case "Flip": FlipFilter flip = new FlipFilter(FlipMode.Horizontal);
                smhelp.SaveImage(source, Img2, _fileName, flip);            
                break;

            case "Warp": WarpFilter warp = new WarpFilter(WarpEffect.Twister, 0.7);
                smhelp.SaveImage(source, Img3, _fileName, warp);            
                break;

            case "Sketch": SketchFilter sktch = new SketchFilter(SketchMode.Gray);
                smhelp.SaveImage(source, Img4, _fileName, sktch);            
                break;

            case "Sepia": SepiaFilter sepia = new SepiaFilter();
                smhelp.SaveImage(source, Img5, _fileName, sepia);            
                break;

            case "MagicPen": MagicPenFilter mgkpen = new MagicPenFilter();
                smhelp.SaveImage(source, Img6, _fileName, mgkpen);            
                break;

            case "Solarize": SolarizeFilter solar = new SolarizeFilter(0.7);
                smhelp.SaveImage(source, Img7, _fileName, solar);            
                break;

            case "Negative": NegativeFilter ngtv = new NegativeFilter();
                smhelp.SaveImage(source, Img8, _fileName, ngtv);            
                break;

            case "TempNTint": TemperatureAndTintFilter temptnt = new TemperatureAndTintFilter(-0.5, 1);
                smhelp.SaveImage(source, Img9, _fileName, temptnt);            
                break;

            case "Stamp": StampFilter stamp = new StampFilter(6, 0.6);
                smhelp.SaveImage(source, Img10, _fileName, stamp);            
                break;
            default:
                break;                        
        }                   
    }
    catch (Exception exception)
    {
        MessageBox.Show("Error Occured, Unable to Save Picture" + exception.Message.ToString());
    }
        
}

As shown in the code, we are using the SaveImage() method from “SaveImageHelper.cs”. Here is the implementation of the SaveImage() Method.

public async void SaveImage(StreamImageSource source, Image Img, String FilterName,IFilter Filter)
{            
using (var imgfilters = new FilterEffect(source))
       {
          var filt = Filter;
          imgfilters.Filters = new IFilter[] { filt };

          var target = new WriteableBitmap((int)Img.ActualWidth, (int)Img.ActualHeight);
          using (var renderer = new WriteableBitmapRenderer(imgfilters, target))
          {
              await renderer.RenderAsync();
              Img.Source = target;
          }

          var jpegRenderer = new JpegRenderer(imgfilters);

          IBuffer jpegOutput = await jpegRenderer.RenderAsync();

          MediaLibrary library = new MediaLibrary();
          _fileName = string.Format("ImageFilta", DateTime.Now.Second) + ".jpg";
          var picture = library.SavePicture(_fileName, jpegOutput.AsStream());
          MessageBox.Show("Image saved!");
        }           
}

Once you click on Save from the AppBar, the image will be saved on your phone and you can check the same in your album.

saved-filters

Sharing Image with Filter Effect on Socials

Social integration is one of the key aspects of this application since the very purpose of this application is to allows users to apply some filters and effects to the images and share them with their friends on the social network. The following code shows how it can be done quickly. Note that this feature totally depends on the Social platform integration configured on your device. It does not explicitly post anywhere else, unless you select to do so.

private void mnuShare_Click(object sender, EventArgs e)
{
var chooser = new Microsoft.Phone.Tasks.PhotoChooserTask();
chooser.Completed += chooser_Completed;
chooser.Show();
}

void chooser_Completed(object sender, PhotoResult e)
{
_fileName = e.OriginalFileName.ToString();
if (e.TaskResult == TaskResult.OK)
{
ShareMediaTask shareMediaTask = new ShareMediaTask();
shareMediaTask.FilePath = _fileName;                
shareMediaTask.Show();
}
}

The application simply makes use of Launchers and Chooser throughout the application. To allow users to select a photo, the PhotoChooserTask class is used and to allow the app to launch a dialog that allows a user to share a media file on the social networks of their choice, the ShareMediaTask class is used. These classes are available in Windows Phone 8.0 SDK out of the box. So this is how you can pick images from Saved Picture and share on Socials sites.

social-share

Summary

There are some Image filtering apps available on the Windows Phone Store like Instagram, 6tag etc. This article has been written with the purpose of guiding you and giving you a roadmap of how such apps can be built using Nokia Imaging SDK. Nokia Imaging SDK is free to download, however if you are using it in your commercial / store ready app, then please check the Terms and Conditions mentioned on the Nokia Imaging SDK Website.

Nokia Imaging SDK provides a simple and easy way to implement APIs and thus makes it easy for developers to plug and play in their apps. We all know that Nokia as a Windows Phone manufacturer comes with an awesome set of Hardware devices which also include a stunning Camera built-into these devices. Nokia Devices like Lumia 920, 1520 and the 1020 in particular, which gives a 41 megapixel camera, are some of the popular Windows Phone devices. In order to enjoy the imaging from such devices, there is always need of image editing and processing. Nokia Imaging SDK gives you access to a powerful library of exciting image-manipulation tools.

Download the entire source code from our GitHub Repository at bit.ly/dncm13-wpnokiasdk

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Author
Vikram Pendse is currently working as a Technology Manager for Microsoft Technologies and Cloud in e-Zest Solutions Ltd. in (Pune) India. He is responsible for Building strategy for moving Amazon AWS workloads to Azure, Providing Estimates, Architecture, Supporting RFPs and Deals. He is Microsoft MVP since year 2008 and currently a Microsoft Azure and Windows Platform Development MVP. He also provides quick start trainings on Azure to startups and colleges during weekends. He is a very active member in various Microsoft Communities and participates as a Speaker in many events. You can follow him on Twitter @VikramPendse


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by ravi kiran on Saturday, September 20, 2014 2:46 AM
please provide croping and adjusting brightness code also
Comment posted by Vikram Pendse on Monday, September 22, 2014 12:53 AM
Hi Ravi,

Thanks for the feedback, I am planning to post an extension of this article to cover more features of Imaging SDK. I will address Croping and other features like Brightness etc. in the same.
Comment posted by Misha on Wednesday, September 24, 2014 10:44 AM
We need more articles on WP 8.1. There is not much to study from online sources and msdn is confusing. I hope you write some good articles on the new features
Comment posted by Vikram Pendse on Sunday, September 28, 2014 11:58 PM
Hi Misha,

I agree and with you that there is not much content on WP8.1. I am not only planning but started drafting few articles, hope you will see some more here. So many things are changing in Windows and Windows Phone and lot many areas to be covered, I will try my best to address most of them in coming days.