C# - Loading an indexed color image file correctly

Viewed 3485

So I created an indexed color, 8 bits-per-pixel PNG (I already checked with ImageMagick if the format is correct) and I want to load it from disk into a System.Drawing.Bitmap while keeping the 8bpp pixel format, in order to view (and manipulate) its palette. However, if I create a Bitmap like this:

Bitmap bitmap = new Bitmap("indexed-image.png");

The resulting Bitmap gets automatically converted to a 32bpp image format, and the bitmap.Palette.Entries field comes out as empty.

An answer to the question "How to convert a 32bpp image to 8bpp in C#?" here on StackOverflow said that this could be a valid way to convert it back to 8bpp:

bitmap = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), PixelFormat.Format8bppIndexed);

This, however, produces incorrect results, as some colors in the palette are just plain wrong.

How can I load an image natively to 8bpp, or at least correctly convert a 32bpp one to 8bpp?

2 Answers
Related