问题
I have the below method which I found online,which resizes an image to an approximate size, while keeping the aspect ratio.
public Image ResizeImage(Size size)
{
int sourceWidth = _Image.Width;
int sourceHeight = _Image.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(_Image, 0, 0, destWidth, destHeight);
g.Dispose();
return (Image)b;
}
I usually pass in a size with a width of 100px and a height of 100px - as part of my requirements I can't have any single dimension (height or width) being under 100px, so if the aspect ratio isn't square the other dimension would be higher.
What I'm finding with this method is occasionally one of the dimensions will be under 100px - such as 96px or 99px. How can I change this method to ensure this doesn't happen?
回答1:
The code is just inappropriate. It doesn't score points for using floating point math, that has a knack for rounding the wrong way so you can easily end up with 99 pixels instead of 100. Always favor integer math so you can control the rounding. And it just doesn't do anything to ensure that one of the dimensions is large enough, the way to end up with 96 pixels. Just write better code. Like:
public static Image ResizeImage(Image img, int minsize) {
var size = img.Size;
if (size.Width >= size.Height) {
// Could be: if (size.Height < minsize) size.Height = minsize;
size.Height = minsize;
size.Width = (size.Height * img.Width + img.Height - 1) / img.Height;
}
else {
size.Width = minsize;
size.Height = (size.Width * img.Height + img.Width - 1) / img.Width;
}
return new Bitmap(img, size);
}
I left a comment to show what you do if you are only want to make sure the image is large enough and accept larger images. It wasn't clear from the question. If that's the case then replicate that if statement in the else clause as well.
来源:https://stackoverflow.com/questions/15998306/resizing-images-in-c-sharp