#WinRT : how to easily get the dominant color of a picture

, , 1 Comment

“Content before Chrome” is the Leitmotif of Windows Store Apps. You’ll usually end up using a lot of images in your app and getting the dominant color of a picture may actually be useful. My first attempt to achieve this was to get the bytes of the picture and calculate the average value. There is actually an easier and faster solution using the Windows Rutime API.

The GetPixelDataAsync method of the BitmapDecoder class lets you get the pixels of a given picture and you can apply transformations during the process. I will the simply ask it to resize the image to a simple unique pixel. The resulting pixel will be the dominant color of the image.

//get the file
var file = await StorageFile.GetFileFromApplicationUriAsync(myLocalImageUri);

using (var stream = await file.OpenAsync(FileAccessMode.Read))
//Create a decoder for the image
var decoder = await BitmapDecoder.CreateAsync(stream);

//Create a transform to get a 1×1 image
var myTransform = new BitmapTransform { ScaledHeight = 1, ScaledWidth = 1 };

//Get the pixel provider
var pixels = await decoder.GetPixelDataAsync(
myTransform ,

//Get the bytes of the 1×1 scaled image
var bytes = pixels.DetachPixelData();

//read the color
var myDominantColor = Color.FromArgb(255, bytes[0], bytes[1], bytes[2]);


The code is extremely simple: open the file, open its stream, create a BitmapDecoder, grab the pixels applying the transform and read the color.
dominant color


One Response

Comments are closed.