How to decode an image (XAML)

[ This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation ]

We show you how to load an image from a file, display it using the Image control, and create a BitmapDecoder object from it. A BitmapDecoder lets you access metadata and get pixel data from images.

For another example of decoding an image, see the Simple Imaging sample.

What you need to know

Technologies

Prerequisites

Instructions

Step 1: Add a placeholder image

Add an Image element to your XAML file.

<Image x:Name="myImage" Source=""/>

You will later set the image file as the source of the myImage object.

Step 2: Use the file picker to pick an image file

Create a new FileOpenPicker object to let the user select a file to be opened. Set the file extension to filter for JPEG images. Then, display the picker.

async void DecodeImage()
{
    var picker = new Windows.Storage.Pickers.FileOpenPicker();
    picker.FileTypeFilter.Add(".jpg");
    var file = await picker.PickSingleFileAsync();

    if (file == null)
    {
        // The user pressed Cancel.
    }

Note  You can get a list of all the file extensions supported by the codecs installed on the system by using Windows.Graphics.Imaging.BitmapDecoder.GetDecoderInformationEnumerator.

 

Note  If the user cancels, the PickSingleFileAsync method returns a null object.

 

Step 3: Display the image in the Image control

Open the file using the Read access mode to get an IRandomAccessStream. Initialize a BitmapImage on this stream and then set it as the source of the Image control.

    var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
    var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
    await bitmapImage.SetSourceAsync(stream);
    myImage.Source = bitmapImage;

Step 4: Create the decoder object

Create a BitmapDecoder object from the stream.

    var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
}

Remarks

Now that you have a decoder object you can use it to:

Simple Imaging sample

Windows.Graphics.Imaging

How to read image metadata

How to get pixel data in the default format

How to get pixel data in a particular format

How to encode an image