Parameter is not valid for new Bitmap in .net

Recently from nowhere we bumped into the error Parameter is not valid for new Bitmap in .net

You get this error when you try to create a new bitmap from a image object. After comparing all the parameters for normal image and error image we identified that the error image was having the pixelformat as 8207 whereas the normal image had pixelformat as Format24bppRgb.

parameter is not valid in new bitmap having PixelFormat 8207

PixelFormat 8207

After reading about this we identified this happens with Indexed Color Images. Color information is not directly carried by image pixel data.

The possible solution for parameter is not valid for new bitmap

we could find was to create a bitmap from image filestream and then clone that bitmap with pixelformat.

So from

Image fileImg = Image.FromStream(fileStream);

We changed it to

Bitmap bm = new Bitmap(fileStream);
Bitmap cloneImg = null;
if (bm.PixelFormat.ToString() == "8207")
{
RectangleF cloneRect = new RectangleF(0, 0, bm.Width, bm.Height);
System.Drawing.Imaging.PixelFormat format = bm.PixelFormat.ToString() == "8207" ? PixelFormat.Format24bppRgb : bm.PixelFormat;
cloneImg = bm.Clone(cloneRect, format);
}
Image fileImg = bm.PixelFormat.ToString() == "8207" ? cloneImg : bm;

After cloning the bitmap object from above code we set the pixelformat for new image to Format24bppRgb which the new Bitmap understand and allows to create an object. We then use this  fileImg object to create a new bitmap object without any parameter is not valid for new bitmap error.

Parameter is not valid for new bitmap before cloning the bitmap

Pixel format before cloning the bitmap

 

Parameter is not valid for new bitmap solved after cloning the bitmap

Pixel format for new image after cloning

If you have any better solution do let me know.