C#: Getting round the "Indexed Pixel Format Issue" in GDI+

by Brad 21. May 2008 09:49

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;
}

Tags:

C#

Comments

2/12/2009 6:04:01 PM #

Thanks for the post Paul. Worked a treat...

Steve Walsh |

2/13/2009 8:30:24 PM #

Thank you. Great solution for the problem.

Ami |

4/20/2009 3:09:06 PM #

Well Done freind - great solution Smile

Tino |

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  July 2010  >>
MoTuWeThFrSaSu
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar