How to get pixel data in the default format (XAML)

We show you how to use a BitmapDecoder object to get pixel data from an image. The pixels are packaged as a byte array and the BitmapDecoder object automatically selects the best format to use.

BitmapDecoder can automatically determine the best fit pixel format for the image and provide pixel data in that format. This can be useful if you are loading images stored in a format, such as JPEG-XR, that supports greater than 8 bit-per-channel precision. If you have BitmapDecoder determine the optimal pixel format, you must detect and handle every possible combination of pixel format and alpha mode, as these are determined at runtime when the image is decoded.

Step 2: Get a pixel data provider object

In this case, the pixel format and alpha mode are automatically determined, EXIF orientation is applied and the pixel data is color managed to sRGB. See GetPixelDataAsync for more info.

Step 3: Handle each pixel format and alpha mode combination

Because the pixel format and alpha mode of the returned pixel data is determined at runtime, your app must detect and handle each potential combination, with its own unique code path. You can determine the pixel format and alpha mode of the returned pixel data by querying the BitmapPixelFormat and BitmapAlphaMode properties on the BitmapDecoder.

In this example, we walk each pixel’s color channel values. So, you must handle different pixel bit depths and channel orderings.

The ProcessPixelArray method, which has two overloads, is part of your app’s code and is defined in the next step.

Note In this example, we handle the Rgba16 pixel format by copying the data into an ushort array. This results in a second in-memory copy of the pixel data. If you are editing a very large image, this will increase the memory consumption of your app.

Step 4: Loop through the pixels

Implement the ProcessPixelArray methods needed to handle each pixel format combination. The code here zeroes out the green and blue channels, leaving the red and alpha channels.

Note The zero parameter overload of GetPixelDataAsync always applies EXIF orientation if the flag is present in the image. So, when getting the dimensions of the image it is important to use the OrientedPixelWidth and OrientedPixelHeight properties, instead of pixelWidth and PixelHeight.
The OrientedPixelWidth and OrientedPixelHeight properties reflect any change in dimensions resulting from EXIF orientation.