Reputation: 6290
I've been trying to change the size of my photo. I've looked at a lot of sites: 1 , 2 , 3.
The last link (3) at least will resize the image except the old image remains behind the resized one. How is this happening? And why? If i minimize the winform and then bring the winform back up, the old image is gone and i'm left with just the resized version. How do i get rid of the old image?
Any ideas?
Upvotes: 2
Views: 3028
Reputation: 81675
That first link from C# Tutorial - Image Editing: Saving, Cropping, and Resizing gave you the code.
Is there a reason not to use it?
private static Image resizeImage(Image imgToResize, Size size)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (Image)b;
}
Don't ignore the InterpolationMode
. It will make the image better looking.
Also, I don't think you want to use CreateGraphics()
in this context. You probably want to use an actual bitmap to store the resized image in or just use the Graphic
object from the paint event of the control you want to show the image in.
Upvotes: 1
Reputation: 3217
Aren't you clearing surface of graphics object? maybe because of that old image still might have been showing. take a look at here http://msdn.microsoft.com/en-us/library/system.drawing.graphics.clear.aspx
Upvotes: 1