Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Convert Bitmap to indexed colour format

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 ?

like image 527
JWood Avatar asked Oct 27 '25 13:10

JWood


2 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.

like image 179
Moon Avatar answered Oct 30 '25 04:10

Moon


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".

like image 31
Semtex Avatar answered Oct 30 '25 03:10

Semtex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!