The Mysterious Invalid Parameter Used Error

Recently I was trying to write a little C# function for cropping images. I expected it to be a quick 5 minute task but I ended up spending a huge amount of time getting it to work correctly. I kept getting a very stubborn and mysterious error - “Invalid Parameter Used” - whenever I tried to save my newly cropped image by doing bitmap.Save(). I tried various suggestions I found on forums and blogs to no avail.

Finally I figured out what the problem was. I was encapulatning the Bitmap and Graphics objects inside a “using” statement. So the Bitmap object was being prematurely disposed before I returned it back to the caller.

So in the end my solution looked like this. I just god rid of the “usings”.

public Bitmap CropImage(Image image, Rectangle cropRect)
{
    Bitmap bitmap = new Bitmap(cropRect.Width, cropRect.Height, PixelFormat.Format24bppRgb);
    bitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution);
    Graphics graphics = Graphics.FromImage(bitmap);
    graphics.DrawImage(image, 0, 0, cropRect, GraphicsUnit.Pixel);
    return bitmap;
}

Usage -
Bitmap croppedBmp = CropImage(”~/uploads/test.jpg”, new Rectangle(x, y, width, height));
croppedBmp.Save();

Moral of the story: If you are getting this error while calling Bitmap.Save() then make sure you are not disposing your Bitmap object prematurely. Hope this helps.

If you have any questions or comments, please post them below. If you liked this post, you can share it with your followers or follow me on Twitter!