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.
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.
If you have any better solution do let me know.