Windows 10 – Universal Windows Platform – Recognition App

Step 1

Download Visual Studio Community 2015 and install it onto your computer, if it’s already downloaded and installed select Launch to start Visual Studio Community 2015 or if it has already been downloaded and installed then start the application you may also need to Enable your device for development.

2015-visual-studio

Step 2

Once Visual Studio Community 2015 has started select File, then New, then Project… from the Menu.

2015-file-new-project

Step 3

From the New Project window select Visual C# from Installed, Templates then select Blank App (Windows Universal) from the list, then type in a Name and select a Location to save to before selecting Ok to create the Project.

2015-new-project

Step 4

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

2015-project-add-new-item

Step 5

From the Add New Item window select Visual C# from Installed and select Code 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

2015-add-new-item-library

Step 6

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

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

public class Library
{
    private const string textExt = ".txt";
    private const string imageExt = ".jpg";

    public async Task<bool> Confirm(string content, string title, string ok, string cancel)
    {
        bool result = false;
        MessageDialog dialog = new MessageDialog(content, title);
        dialog.Commands.Add(new UICommand(ok, new UICommandInvokedHandler((cmd) => result = true)));
        dialog.Commands.Add(new UICommand(cancel, new UICommandInvokedHandler((cmd) => result = false)));
        await dialog.ShowAsync();
        return result;
    }

    public async void New(TextBox display)
    {
        if (await Confirm("Create New?", "Recognition App", "Yes", "No"))
        {
            display.Text = string.Empty;
        }
    }

    public async void Open(Image source, TextBox target)
    {
        try
        {
            FileOpenPicker picker = new FileOpenPicker();
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.FileTypeFilter.Add(textExt);
            picker.FileTypeFilter.Add(imageExt);
            StorageFile file = await picker.PickSingleFileAsync();
            switch (file.FileType)
            {
                case textExt:
                    target.Text = await FileIO.ReadTextAsync(file);
                    break;
                case imageExt:
                    using (IRandomAccessStream stream = await file.OpenReadAsync())
                    {
                        BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(stream);
                        SoftwareBitmap softwareBitmap = await bitmapDecoder.GetSoftwareBitmapAsync(
                            BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
                        OcrEngine engine = OcrEngine.TryCreateFromLanguage(new Language("en-us"));
                        OcrResult ocrResult = await engine.RecognizeAsync(softwareBitmap);
                        target.Text = ocrResult.Text;
                        stream.Seek(0);
                        BitmapImage image = new BitmapImage();
                        image.SetSource(stream);
                        source.Source = image;
                    }
                    break;
                default:
                    break;
            }
        }
        catch
        {

        }
    }

    public async void Save(Image source, TextBox target)
    {
        try
        {
            FileSavePicker picker = new FileSavePicker();
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.FileTypeChoices.Add("Image File", new List<string>() { imageExt });
            picker.FileTypeChoices.Add("Text File", new List<string>() { textExt });
            picker.DefaultFileExtension = textExt;
            StorageFile file = await picker.PickSaveFileAsync();
            switch (file.FileType)
            {
                case textExt:
                    await FileIO.WriteTextAsync(file, target.Text);
                    break;
                case imageExt:
                    using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
                        RenderTargetBitmap render = new RenderTargetBitmap();
                        await render.RenderAsync(target);
                        IBuffer buffer = await render.GetPixelsAsync();
                        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                        (uint)render.PixelWidth, (uint)render.PixelHeight, 96.0, 96.0, buffer.ToArray());
                        await encoder.FlushAsync();
                        target = null;
                        buffer = null;
                        encoder = null;
                    }
                    break;
                default:
                    break;
            }
        }
        catch
        {

        }
    }

    public void Sample(TextBox target)
    {
        target.Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris non massa diam. " +
            "Nunc luctus non lorem id imperdiet. Nunc quis mi nec enim malesuada commodo mollis eget nisl. " +
            "Sed vulputate in purus eu vulputate. Quisque commodo eu odio et malesuada. Duis porttitor, " +
            "lectus ut egestas placerat, purus nisi elementum diam, congue lacinia erat lectus sit amet felis. " +
            "Proin suscipit lobortis bibendum. Aliquam erat volutpat. Nunc vitae nulla nunc.";
    }
}

It should then appear as such:

2015-recognition-app-library

Step 7

From the Solution Explorer select MainPage.xaml

2015-mainpage-library

Step 8

Select from the Menu, View then Designer

2015-view-designer

Step 9

The Design View will be displayed along with the XAML View and in this above <Grid Background=”{ThemeResource ApplicationPageBackgroundThemeBrush}”> enter the following XAML:

<Page.BottomAppBar>
	<AppBar IsOpen="True" IsSticky="True">
		<StackPanel Orientation="Horizontal">
			<AppBarButton Icon="Page" Label="New" Click="New_Click"/>
			<AppBarButton Icon="Folder" Label="Open" Click="Open_Click"/>
			<AppBarButton Icon="Save" Label="Save" Click="Save_Click"/>
			<AppBarButton Icon="Document" Label="Sample" Click="Sample_Click"/>
		</StackPanel>
	</AppBar>
</Page.BottomAppBar>

While still in the XAML View below <Grid Background=”{ThemeResource ApplicationPageBackgroundThemeBrush}”> enter the following XAML:

<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
	<Grid.RowDefinitions>
		<RowDefinition Height="50*"/>
		<RowDefinition Height="50*"/>
	</Grid.RowDefinitions>
	<Image Grid.Row="0" Name="Source"/>
	<TextBox Grid.Row="1" Name="Target" AcceptsReturn="True" TextWrapping="Wrap"/>
</Grid>

It should appear as such:

2015-recognition-app-mainpage-xaml

Step 10

Select from the Menu, View then Code

2015-view-code

Step 11

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

public Library Library = new Library();

private void New_Click(object sender, RoutedEventArgs e)
{
	Library.New(Target);
}

private void Open_Click(object sender, RoutedEventArgs e)
{
	Library.Open(Source, Target);
}

private void Save_Click(object sender, RoutedEventArgs e)
{
	Library.Save(Source, Target);
}

private void Sample_Click(object sender, RoutedEventArgs e)
{
	Library.Sample(Target);
}

It should then appear as such:

2015-recognition-app-mainpage-code

Step 12

That completes the Universal Windows Application so Save the Project then select the Debug and Simulator option to run the Application

2015-simulator

Step 13

Once the Simulator has started the Application should then appear

2015-recognition-app-simulator-run

Step 14

After the Application has started running you can enter any text then use Save to store a Image file of the text, then Open to Recognise a stored Image file as text in the Application

2015-recognition-app-simulator-ran

Step 15

To Exit the application select Stop Debugging in Visual Studio Community 2015

2015-stop

Step 16

Another option is to run as a Windows 10 Mobile application, select Debug and select Emulator 10.0.10586.0 WVGA 4 inch 512MB option to run the Application

2015-emulator

Step 17

Once the Emulator has started the Application should then appear

2015-recognition-app-emulator-run

Step 18

After the Application has started running you can enter any text then use Save to store a Image file of the text, then Open to Recognise a stored Image file as text in the Application

2015-recognition-app-emulator-ran

Step 19

To Exit the application select Stop Debugging in Visual Studio Community 2015

2015-stop

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s