How to decode an image (HTML)

[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 <img> tag, and create a BitmapDecoder object from it. A BitmapDecoder lets you access metadata and get pixel data from images.

What you need to know

Technologies

Prerequisites

Instructions

Step 1: Add a placeholder image

Add a <img> tag to your HTML file.

<img id="myImage" src="" />

You will later load the image file into 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.

function DecodeImage() {
    var picker = new Windows.Storage.Pickers.FileOpenPicker();
    picker.fileTypeFilter.append(".jpg");
    picker.pickSingleFileAsync().then(function (file) {
        if (!file) {

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 element

Create an object URL for the file and set it as the source of the Image element.

The createObjectURL method creates a URL that is backed by data from an object such as StorageFile.

            var objectURL = window.URL.createObjectURL(file, { oneTimeOnly: true });
            document.getElementById("myImage").src = objectURL;

Step 4: Create the decoder object

Open the file using the Read access mode to get an IRandomAccessStream. Then create a BitmapDecoder object on the stream.

    }).then(function (stream) {
        return Windows.Graphics.Imaging.BitmapDecoder.createAsync(stream);
    }).done(function (decoder) {
        // BitmapDecoder is ready for use.
    });
}

Remarks

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

How to read image metadata

How to get pixel data

How to encode an image

Windows.Graphics.Imaging