Color Reduction in WPF

September 27, 2008

Sometimes we need to reduce colors in image by some reasons. WPF has built-in ability to reduce colors of the image. FormatConvertedBitmap class was design to perform such operations. Let’s take a look on the following code, which is part of demo available to download:

FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
newFormatedBitmapSource.BeginInit();
//Set source from image control
newFormatedBitmapSource.Source = iSource.Source as BitmapSource;

//Create palette of requied color. Pay heed to maxColorCount it can have any value, but PixelFormats supports only 2,4,16 and 256 colors.
BitmapPalette myPalette = new BitmapPalette(iSource.Source as BitmapSource, int.Parse(cbNumberOfColors.SelectionBoxItem as string));

newFormatedBitmapSource.DestinationPalette = myPalette;

//Set PixelFormats
newFormatedBitmapSource.DestinationFormat = PixelFormats.Indexed8;
newFormatedBitmapSource.EndInit();

iReduced.Source = newFormatedBitmapSource;

There are two important moments here. First,

//Create palette of requied color. Pay heed to maxColorCount it can have any value, but PixelFormats supports only 2,4,16 and 256 colors.
BitmapPalette myPalette = new BitmapPalette(iSource.Source as BitmapSource, int.Parse(cbNumberOfColors.SelectionBoxItem as string));

As you can see, we create Palette from source image. In the second parameter of the constructor we passing the desired number of colors. It creates palette with desired number of colors. Sweet. How does that works? I used reflector to find out. It uses IWICPalette_InitializeFromBitmap_Proxy function from windowscodecs.dll. This function has the following remark:

“The resulting palette contains the specified number of colors which best represent the colors present in the bitmap (according to the algorithm we use). The algorithm operates on the opaque RGB color value of each pixel in the reference bitmap and hence ignores any alpha values. If a transparent color is required, set the fAddTransparentColor parameter to TRUE and one fewer optimized color will be computed and a fully transparent color entry will be added.

This method is particularly useful with the error diffusion dithering algorithm described in the format conversion section.”

They don’t specify, which algorithm is used (  Official documentation has the following hint:

“They are intended to provide the best possible image quality with a reduced set of colors. Optimal palettes are generated from an image’s pixel values – usually using a histogram.”

So, we have palette now. Next, we need to assign indexes to all pixels from palette. If you take a look on the code, you probably didn’t find line, which suppose to assign indexes to pixels. I used to reflector to find out where it happens. Method FormatConvertedBitmap.EndInit calls virtual FinalizeCreation, which calls IWICFormatConverter_Initialize_Proxy from windowscodecs.dll. This function do the trick. It assigns indexes to pixels.

At the last part, I show you screen of the demo program and will give some comments.

Color reduction sample

Color reduction sample

This demo very simple. You can load image from hard disc to the left image box and convert it to the right image box by pressing “Convert” button. Save button allows you to save result on you hd. Combobox specifies desired number of colors.

You also can download whole VS2008 project in the zip archive. Change it’s extension, it is zip not pdf.

PS If somebody knows algorithms, which is used in windowscodecs.dll, please let me know, i will appreciate this.

3 Responses to “Color Reduction in WPF”

  1. Andrey said

    > PS If somebody knows algorithms, which is used in windowscodecs.dll, please let me know, i will appreciate this.

    Не совсем ясно, тебе интересна рабочая реализация алгоритма редуции цветов, или конкретные алгоритмы именно из windowscodecs.dll?

  2. iyalovoi said

    мне интересно какие алгоритмы редуции цветов использует виндоус, потому что тогда можно было бы оценить их минусы и знать в каких задачах лучше использовать другие.

  3. Andrey said

    ага, ясно.
    кстати, где же давно обещанная статья по моделированию?
    или решил не писать?

Leave a Reply