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.

why a developer should not be interrupted while coding?

Why a developer should not be interrupted while coding?

Here is the small conversation that will explain you

“How long does it take for you to fall asleep?”

“X minutes”

“Now imagine that when you are close to falling asleep, someone walks in and interrupts you, how long will it take you to fall asleep now? Those few seconds you had left, or will you have to start again to ‘sink back’ to where you were?”

“I’ll have to start again”

“Great. Same thing. Just like falling asleep, it takes me a while to ‘sink’ into focus mode, and it takes me a while to get back to it once I’m interrupted, except that I also forget half of what I was doing.”

why a developer should not be interrupted while coding?

Don’t Interrupt