If you've ever tried to manipulate images in C# using GDI+ you'll almost certainly have come across the following error at some point:
a graphics object cannot be created from an image that has an indexed pixel format
I know I have, and it took a fair bit of effort to find the solution so I thought I'd share it.
Here's a quick background on Pixel Formats... In 'Non Indexed' images, each pixel represents ONE colour. So a pixel might have a value &h0000FF (Red). In 'Indexed' images each pixel value is an index to a so-called 'palette' or 'colour table'. So a pixel might have a value of 3, which means use the colour in palette entry #3 for that pixel.
For some reason GDI+ doesn't support editing Indexed images (that use the palette/colour table approach).
Here's a simple work around which, if the Pixel Format is Indexed, will create a new (non-indexed) Bitmap image from the original image instance
Image original = Image.FromFile(SourceImagePath);
switch (original.PixelFormat)
{
case System.Drawing.Imaging.PixelFormat.Undefined:
case System.Drawing.Imaging.PixelFormat.Format1bppIndexed:
case System.Drawing.Imaging.PixelFormat.Format4bppIndexed:
case System.Drawing.Imaging.PixelFormat.Format8bppIndexed:
case System.Drawing.Imaging.PixelFormat.Format16bppGrayScale:
case System.Drawing.Imaging.PixelFormat.Format16bppArgb1555:
// Create a new BitMap object using original Image instance
original = new Bitmap(original);
break;
}