Universal Windows Platform – Photo Rotate

Photo Rotate demonstrates how to use BitmapTransform and related Properties and Methods to create a simple image-rotating application

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.

vs2017

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in a Name and select a Location and then select Ok to create the Project
vs2017-new-project-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates

Step 5

Once done select from the Menu, Project, then Add New Item…

vs2017-project-add-new-item

Step 6

From the Add New Item window select Visual C#, then Code from Installed then select Code File from the list, then type in the Name as Library.cs before selecting Add to add the file to the Project

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

public class Library
{
    private int _angle;
    private StorageFile _file;
    private WriteableBitmap _bitmap;

    private readonly Dictionary<int, BitmapRotation> rotation_angles = 
        new Dictionary<int, BitmapRotation>()
    {
        { 0, BitmapRotation.None },
        { 90,  BitmapRotation.Clockwise90Degrees },
        { 180,  BitmapRotation.Clockwise180Degrees },
        { 270, BitmapRotation.Clockwise270Degrees },
        { 360, BitmapRotation.None }
    };
    private const string file_extension = ".jpg";

    private async Task<WriteableBitmap> ReadAsync()
    {
        using (IRandomAccessStream stream = await _file.OpenAsync(FileAccessMode.ReadWrite))
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(BitmapDecoder.JpegDecoderId, stream);
            uint width = decoder.PixelWidth;
            uint height = decoder.PixelHeight;
            if (_angle % 180 != 0)
            {
                width = decoder.PixelHeight;
                height = decoder.PixelWidth;
            }
            BitmapTransform transform = new BitmapTransform
            {
                Rotation = rotation_angles[_angle]
            };
            PixelDataProvider data = await decoder.GetPixelDataAsync(
            BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, transform,
            ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);
            _bitmap = new WriteableBitmap((int)width, (int)height);
            byte[] buffer = data.DetachPixelData();
            using (Stream pixels = _bitmap.PixelBuffer.AsStream())
            {
                pixels.Write(buffer, 0, (int)pixels.Length);
            }
        }
        return _bitmap;
    }

    private async void WriteAsync()
    {
        using (IRandomAccessStream stream = await _file.OpenAsync(FileAccessMode.ReadWrite))
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
            (uint)_bitmap.PixelWidth, (uint)_bitmap.PixelHeight, 96.0, 96.0, _bitmap.PixelBuffer.ToArray());
            await encoder.FlushAsync();
        }
    }

    public async void OpenAsync(Image display)
    {
        _angle = 0;
        try
        {
            FileOpenPicker picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };
            picker.FileTypeFilter.Add(file_extension);
            _file = await picker.PickSingleFileAsync();
            if (_file != null)
            {
                display.Source = await ReadAsync();
            }
        }
        catch
        {

        }
    }

    public async void SaveAsync()
    {
        try
        {
            FileSavePicker picker = new FileSavePicker
            {
                DefaultFileExtension = file_extension,
                SuggestedFileName = "Picture",
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };
            picker.FileTypeChoices.Add("Picture", new List<string>() { file_extension });
            _file = await picker.PickSaveFileAsync();
            if (_file != null)
            {
                WriteAsync();
            }
        }
        catch
        {

        }
    }

    public async void RotateAsync(Image display)
    {
        if (_angle == 360) _angle = 0;
        _angle += 90;
        display.Source = await ReadAsync();
    }
}

In the Library.cs there are using statements to include the necessary functionality. There is an int to store the rotation angle, then a StorageFile to get or set the File of the photo and a Dictionary to store the supported rotation angles. The ReadAsync Method is used to get an IRandomAccessStream from this File and get the image with a BitmapDecoder. The photo is then manipulated to introduce a transformation – in this case the rotation with the PixelDataProvider and this information is then written back to the File to produce the rotated image. The WriteAsync Method is used encode any resulting image as the correct format with BitmapEncoder set to the settings optimised for a photo. OpenAsync is used to get a photo with a FileOpenPicker and calls the ReadAsync to get the File and set the Source of the Image passed in. The SaveAsync Method is use to store a photo after it has be rotated with the FileSavePicker used along with the WriteAsync Method. RotateAsync is used to rotate the image and increments the value to be used by 90 degrees each time it is called up to 360 degrees when it is reset, the image is then obtained again with this rotation using the ReadAsync Method.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

Step 9

From the Menu choose View and then Designer

vs2017-view-designer

Step 10

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" ZoomMode="Enabled">
	<Image Name="Display"/>
</ScrollViewer>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Name="Open" Icon="OpenFile" Label="Open" Click="Open_Click"/>
	<AppBarButton Name="Save" Icon="Save" Label="Save" Click="Save_Click"/>
	<AppBarButton Name="Rotate" Icon="Rotate" Label="Rotate" Click="Rotate_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a ScrollViewer containing an Image Control that can be zoomed in or out of so you can view the image at any needed size with pinch-to-zoom or scroll-wheel. The second block of XAML is is the CommandBar which contains Open – to read and show a photo in the Image Control and Save to write a photo after it has been rotated and finally Rotate to perform the rotation.

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:

Library library = new Library();

private void Open_Click(object sender, RoutedEventArgs e)
{
	library.OpenAsync(Display);
}

private void Save_Click(object sender, RoutedEventArgs e)
{
	library.SaveAsync();
}

private void Rotate_Click(object sender, RoutedEventArgs e)
{
	library.RotateAsync(Display);
}

Below the MainPage() Method an instance of the Library Class is created, then Open_Click is used to call the OpenAsync method to get a photo, SaveAsync is used to store a photo and RotateAsync is used to perform the rotation of the photo.

Step 13

That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-local-machine

Step 14

After the Application has started running you can use Open to select a Photo to Rotate after which you can then Save the rotated photo

ran-photo-rotate

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s