Quick Start for Windows

Create a new project

To create a new project, follow these steps:

  1. In Visual Studio, click File > New > Project...
  2. In the New Project window, select Visual C# > Windows > Universal > Blank App (Universal Windows).
  3. Click OK.

A project has now been created for you.

Include libraries to your project

Before you start to use the functionality provided by the SDK, the Lumia Imaging SDK libraries must be added to the project. For detailed instructions, see the chapter Adding libraries to the project.

Define your XAML UI

The UI we will build for this tutorial is very simple. There will be two XAML image controls and two buttons. One XAML image control will display the original image, and the other will display the filtered image. Similarly, one button is used for selecting the image, and the other one is used for saving the filtered image to the phone library.

Mt598522.QuickStart(en-us,WIN.10).png

Here are the steps to accomplish this:

  1. Move MainPage.xaml and MainPage.xaml.cs to the QuickStart.Shared project to share as much as possible, even the UI.
  2. In the Solution Explorer pane in Visual Studio, open MainPage.xaml.
  3. Add all the controls that make our UI. In the XAML view, search for the layout root grid that was generated when creating the project:
<Grid>

</Grid>

Replace the grid and all its content with this grid:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <TextBlock Text="Quick Start" Margin="4,4,0,4" FontSize="32"></TextBlock>
    <StackPanel Grid.Row="1">
        <SwapChainPanel x:Name="SwapChainPanelTarget" Grid.Row="1" Width="500" Height="500"/>
        <TextBlock Text="Brightness" Margin="20,0,0,0"/>
        <Slider Minimum="-1.0" Maximum="1.0" StepFrequency="0.1" ValueChanged="OnBrightnessChanged" Margin="20,0" ></Slider>
    </StackPanel>
    <Image x:Name="OriginalImage" Grid.Row="1" Width="200" Height="200" Stretch="Uniform"
            HorizontalAlignment="Left" VerticalAlignment="Top" Margin="12,12,0,0" />

    <Button Content="Pick an image" Click="PickImage_Click" HorizontalAlignment="Left" Grid.Row="2" />
    <Button Content="Save the image" Click="SaveImage_Click" x:Name="SaveButton" HorizontalAlignment="Right" Grid.Row="2" IsEnabled="False" />
</Grid>

In the preceding snippet, we define the preview images, one OriginalImage and one SwapChainPanel SwapChainPanelTarget, without specifying any source for the image to display. We will bind the image source later; code examples will also be given in the chapters below.

Pick an image from the camera roll

Mt598522.quickstart_wp81_choose_file(en-us,WIN.10).png

To pick the image, we will use the FileOpenPicker, which is part of the SDK.

Next, open MainPage.xaml.cs to add the code to pick the image and save the image.

private void PickImage_Click(object sender, RoutedEventArgs e)
{
    SaveButton.IsEnabled = false;
    var openPicker = new FileOpenPicker
    {
        SuggestedStartLocation = PickerLocationId.PicturesLibrary,
        ViewMode = PickerViewMode.Thumbnail
    };

    // Filter to include a sample subset of file types.
    openPicker.FileTypeFilter.Clear();
    openPicker.FileTypeFilter.Add(".bmp");
    openPicker.FileTypeFilter.Add(".png");
    openPicker.FileTypeFilter.Add(".jpeg");
    openPicker.FileTypeFilter.Add(".jpg");

    PickImage(openPicker);
}

Note the last call to PickImage, which does not exist yet, but will be added to a specific partial implementation for each platform.

private void SaveImage_Click(object sender, RoutedEventArgs e)
{
    SaveButton.IsEnabled = false;

    var savePicker = new FileSavePicker()
    {
        SuggestedStartLocation = PickerLocationId.PicturesLibrary,
        SuggestedFileName = string.Format("CartoonImage_{0}", DateTime.Now.ToString("yyyyMMddHHmmss"))
    };

    savePicker.FileTypeChoices.Add("JPG File", new List<string> { ".jpg" });
    SaveImage(savePicker);
}  

Note the last call to SaveImage, which does not exist yet, but will be added to a specific partial implementation for each platform.

Now, create a new class in each platform project, for example, MainPage.cs.
Add the following code:

private async void PickImage(FileOpenPicker openPicker)
{
    // Open the file picker.
    StorageFile file = await openPicker.PickSingleFileAsync();

    // File is null if the user cancels the file picker.
    if (file != null)
    {
        if (!(await ApplyEffectAsync(file)))
            return;

        SaveButton.IsEnabled = true;
    }
}

private async void SaveImage(FileSavePicker savePicker)
{
    var file = await savePicker.PickSaveFileAsync();
    if (file != null)
    {
        await SaveImageAsync(file);
    }

    SaveButton.IsEnabled = true;
}

Now, we are ready to start using the Lumia Imaging SDK.

Add the following using directives:

using Lumia.Imaging;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Popups;
using Windows.UI.Xaml.Media.Imaging;

In the MainPage.xaml.cs class, declare the following member variables.

public partial class MainPage : Page
{
        private GrayscaleEffect _grayscaleEffect;
        private BrightnessEffect _brightnessEffect;
        private SwapChainPanelRenderer m_renderer;

        // The following  WriteableBitmap contains
        // the filtered and thumbnail image.
        private WriteableBitmap _writeableBitmap;
        private WriteableBitmap _thumbnailImageBitmap;
}

Next, we have to initialize the private members that we have just declared. We will initialize them in the constructor.

The **_grayscaleEffect** will be the ImageProvider to the Brightness effect. We also create the SwapChainPanelRenderer with the Brightness effect as ImageProvider.

public Mainpage()
{
    this.InitializeComponent()

    double scaleFactor = 1.0;
    scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;

    _writeableBitmap = new WriteableBitmap((int)(Window.Current.Bounds.Width * scaleFactor), (int)(Window.Current.Bounds.Height * scaleFactor));
    _thumbnailImageBitmap = new WriteableBitmap((int)OriginalImage.Width, (int)OriginalImage.Height);
    _grayscaleEffect = new GrayscaleEffect();
    _brightnessEffect = new BrightnessEffect(_grayscaleEffect);
    m_renderer = new SwapChainPanelRenderer(_brightnessEffect, SwapChainPanelTarget);

    LoadDefaultImageAsync();
}

private async void LoadDefaultImageAsync()
{
    var file = await StorageFile.GetFileFromApplicationUriAsync(new System.Uri("ms-appx:///Assets/defaultImage.jpg"));
    await ApplyEffectAsync(file);
}

Once the image is selected, we can apply the effect on the image. In this tutorial, we apply the Grayscale effect, which is combined with Brightness effect, and display the result in XAML SwapChainPanel control (SwapChainPanelTarget). The complete code of the ApplyEffectAsync method becomes:

private async Task<bool> ApplyEffectAsync(StorageFile file)
{
    // Open a stream for the selected file.
    IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read);

    string errorMessage = null;

    try
    {
        // Show a thumbnail of the original image.
        _thumbnailImageBitmap.SetSource(fileStream);
        OriginalImage.Source = _thumbnailImageBitmap;

        // Rewind the stream to start.
        fileStream.Seek(0);

        // Set the imageSource on the effect and render.
        ((IImageConsumer)_grayscaleEffect).Source = new Lumia.Imaging.RandomAccessStreamImageSource(fileStream);
        await m_renderer.RenderAsync();

    }
    catch (Exception exception)
    {
        errorMessage = exception.Message;
    }

    if (!string.IsNullOrEmpty(errorMessage))
    {
        var dialog = new MessageDialog(errorMessage);
        await dialog.ShowAsync();
        return false;
    }

    return true;
}

First, we set the image stream from the selected image to **_thumbnailImageBitmap** without applying any effect to get the thumbnail of the original image. The next line resets the position of the stream to the beginning. This step is necessary, as the current reading position of the stream will be at the end as a result of the previous step. Next, we create a RandomAccessStreamImageSource with the selected file, and set the source on the **_grayscaleEffect**.

The filtered image is then rendered to the SwapChainPanelTarget.

Add capabilities

Because the application reads data from the Pictures folder, it
needs certain capabilities. In the Solution Explorer pane in Visual Studio,
open the Package.appxmanifest and open the Capabilities tab. Make
sure that the Pictures Library capability is checked.

Rendering and encoding to full resolution JPEG

Rendering to full resolution output JPEG is simple once we have an
instance of GrayScaleEffect. Every pixel of the original image will be
processed by the library and then saved as a JPEG.

This code example demonstrates how to add the functionality to save the
filtered image as a full resolution JPEG:

private async Task<bool> SaveImageAsync(StorageFile file)
{
    if (_grayscaleEffect == null)
    {
        return false;
    }

    string errorMessage = null;

    try
    {
        using (var jpegRenderer = new JpegRenderer(_grayscaleEffect))
        using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            // Jpeg renderer gives the raw buffer that contains the filtered image.
            IBuffer jpegBuffer = await jpegRenderer.RenderAsync();
            await stream.WriteAsync(jpegBuffer);
            await stream.FlushAsync();
        }
    }
    catch (Exception exception)
    {
        errorMessage = exception.Message;
    }

    if (!string.IsNullOrEmpty(errorMessage))
    {
        var dialog = new MessageDialog(errorMessage);
        await dialog.ShowAsync();
        return false;
    }
    return true;
}

Running the application

To run the application:

  1. In the standard toolbar in Visual Studio, select Device or Emulator, and then select Debug.
  2. Build the application.
  3. Connect a device (if you are deploying it on device) and run the application.
  4. Select an image using the Pick an image button.
  5. You should see the main page that contains the decoded image with a Cartoon style effect added.

Tip:
If you are testing an app on an emulator, you may experience an emulator bug. If your app can't see any content in the pictures library, it is likely a result of a bug in the emulator.

If you need to access the in-built images, you need to open the Photos app at least once before you begin testing your application. Once you browse through the photos, the content will become available to your app.

Check out the project in GitHub

Check out our open source project Lumia Imaging SDK in GitHub: Lumia Imaging SDK Git repository

Or get the complete source code of the tutorial: Lumia Imaging Quick Start

Show: