I have an application I have been buidling for awhile and have finally finished the first draft of it (it's a screensaver). Anyway, during my countless hours of testing never once did I see an error this error I am getting now.
The error I am getting only occurs when the application is not running in Debugging mode. The error is as follows
"System.ArgumentException: Parameter is not valid.
at System.Drawing.Image.get_Width()"
And here's the code t's refereing to
public static Image ResizeCenter (Image value, int MaxWidth, int MaxHeight) //just like above, except this centers the image
{
lock (ImageCenterLock)
{
bool WidthLarger = false; //notes if we resized because the width was greater then the height
decimal NewHeight = 0;
decimal NewWidth = 0;
if (((decimal) MaxWidth / (decimal) value.Width) < ((decimal) MaxHeight / (decimal) value.Height)) //if the height difference is greater then the width (landscape)
{
WidthLarger = false;
NewWidth = (((decimal) value.Width) * ((decimal) MaxWidth / value.Width)); //resize to the Width
NewHeight = (((decimal) value.Height) * ((decimal) MaxWidth / value.Width));
}
else //width difference is greater then height (portrait)
{
WidthLarger = true;
NewWidth = (((decimal) value.Width) * ((decimal) MaxHeight / (decimal) value.Height)); //resize to the Height
NewHeight = (((decimal) value.Height) * ((decimal) MaxHeight / (decimal) value.Height));
}
Image TempImage = new Bitmap((int) Math.Floor((double) MaxWidth), (int) Math.Floor((double) MaxHeight)); //creates a image to the max size (that we then center in)
using (Graphics graphicsHandle = Graphics.FromImage(TempImage)) //resizes the image
{
graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphicsHandle.PixelOffsetMode = PixelOffsetMode.HighQuality;
if (WidthLarger == true) //center the x-axis
{
graphicsHandle.DrawImage(value, ((int) ((MaxWidth - NewWidth) / 2)), 0, ((int) Math.Floor(NewWidth)), ((int) Math.Floor(NewHeight)));
}
else //center the y-axis
{
graphicsHandle.DrawImage(value, 0, ((int) ((MaxHeight - NewHeight) / 2)), ((int) Math.Floor(NewWidth)), ((int) Math.Floor(NewHeight)));
}
}
value.Dispose(); //clear out the passed in image (seems to drastically reduce memory usage)
return TempImage;
}
}
Now here's the thing. If I were to comment out that value.Dispose();
, the errors go away. The errors occur predicatably. They throw on the 2nd image, 7th, 14th, ext. Again this has no problem running in debugging mode, but the minute I run it without debugging I have a problem. I need to dispose of those images or else I get a nasty leak that shoots my resources up to GBs.
(Also, the value passed in is tied to a UserControl as a value you can get/set, and on return is plug into a PictureBox).
Any help would be greatly apprecaited. These images have become more and more headaches as they insist on referencing so much and chew up resources.