How can I convert a 24-bit colour System.Drawing.Bitmap
to an indexed (256-colour) format? I'm having trouble working out how to calculate the palette. I can iterate over the pixels and use an int[]
to contain the various colours but the problem comes when there are more than 256 colours. Is there a way to convert to an indexed format and extract a 256-colour palette from an Bitmap
?

- 2,804
- 2
- 39
- 64
-
You should first choose what kind of indexed bitmap do you require. Do you have <= 256 colors to start with? – Daniel Mošmondor Jan 25 '12 at 22:31
5 Answers
Using the Bitmap Clone Method you can directly convert the Source Image to a 256 color Palette Indexed image like this:
Bitmap Result = Source.Clone(new Rectangle(0, 0, Source.Width, Source.Height), PixelFormat.Format8bppIndexed);
Then if you want access the Palette Colors, just use the Result.Palette.Entries
property.

- 1,141
- 2
- 11
- 25
I had the same challenge earlier. It's possible to solve using GDI+ in .Net.
This article helped me a lot (including samples): http://msdn.microsoft.com/en-us/library/Aa479306
For best quality use "Octree-based Quantization".

- 366
- 3
- 3
WPF has access to the Windows Imaging Component, from there you can use a FormatConvertedBitmap to convert the image to a new pixel format. WIC is much much faster than the System.Drawing methods on Vista and 7 and will allow you a lot more options.

- 5,108
- 2
- 33
- 51
This is not built-in but you can either use external .NET libraries for this or shell out to the console to invoke ImageMagic.

- 168,620
- 35
- 240
- 369
-
Actually it is available in WPF via [FormatConvertedBitmap](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.formatconvertedbitmap.aspx) – Mgetz Jan 25 '12 at 22:28
Some reading material to get you started.
Graphic Gems I pp. 287-293, "A Simple Method for Color Quantization: Octree Quantization"
B. Kurz. Optimal Color Quantization for Color Displays. Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, 1983, pp. 217-224.
Graphic Gems II pp. 116-125, "Efficient Inverse Color Map Computation"
This paper describes an efficient technique to map actual colors to a reduced color map, selected by some other technique described in the other papers.
Graphic Gems II pp. 126-133, "Efficient Statistical Computations for Optimal Color Quantization"
Xiaolin Wu. Color Quantization by Dynamic Programming and Principal Analysis. ACM Transactions on Graphics, Vol. 11, No. 4, October 1992, pp 348-372.