我在网上找到了以下方法,可以将图像大小调整为近似大小,同时保持纵横比。
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;
}
我通常传递宽度为 100 像素、高度为 100 像素的尺寸 - 作为我要求的一部分,我不能让任何单个尺寸(高度或宽度)低于 100 像素,所以如果长宽比不低于平方其他尺寸会更高。
我使用此方法发现,有时其中一个尺寸会低于 100 像素 - 例如 96 像素或 99 像素。如何更改此方法以确保不会发生这种情况?
最佳答案
该代码不合适。它不会因使用 float 学而得分, float 学有一种以错误方式舍入的技巧,因此您可以轻松地得到 99 像素而不是 100。始终支持整数数学,以便您可以控制舍入。它只是没有做任何事情来确保其中一个维度足够大,从而最终得到 96 像素。只需编写更好的代码即可。喜欢:
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);
}
我留下了一条评论,以展示如果您只想确保图像足够大并接受更大的图像,您会做什么。从问题中还不清楚。如果是这种情况,那么也在 else 子句中复制该 if 语句。
关于c# - 在 C# 中调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15998306/