图像大小调整算法

Mar*_*ius 11 algorithm resize image

我想编写一个函数来缩小图像的大小以适应指定的边界.例如,我想调整2000x2333图像的大小以适应1280x800.必须保持纵横比.我想出了以下算法:

NSSize mysize = [self pixelSize]; // just to get the size of the original image
int neww, newh = 0;
float thumbratio = width / height; // width and height are maximum thumbnail's bounds
float imgratio = mysize.width / mysize.height;

if (imgratio > thumbratio)
{
    float scale = mysize.width / width;
    newh = round(mysize.height / scale);
    neww = width;
}
else
{
    float scale = mysize.height / height;
    neww = round(mysize.width / scale);
    newh = height;
}
Run Code Online (Sandbox Code Playgroud)

它似乎工作.好吧......好像.但后来我试图将1280x1024图像调整为1280x800边界,它给了我1280x1024的结果(显然不适合1280x800).

有没有人有任何想法这个算法应该如何工作?

GWW*_*GWW 26

我通常这样做的方法是查看原始宽度和新宽度之间的比率以及原始高度和新高度之间的比率.

此后缩小图像的比例最大.例如,如果要将800x600图像调整为400x400图像,则宽度比率为2,高度比率为1.5.以2的比例缩小图像可得到400x300的图像.

NSSize mysize = [self pixelSize]; // just to get the size of the original image
int neww, newh = 0;
float rw = mysize.width / width; // width and height are maximum thumbnail's bounds
float rh = mysize.height / height;

if (rw > rh)
{
    newh = round(mysize.height / rw);
    neww = width;
}
else
{
    neww = round(mysize.width / rh);
    newh = height;
}
Run Code Online (Sandbox Code Playgroud)


And*_*erd 8

这是解决问题的方法:

您知道图像的高度或宽度将等于边界框的高度或宽度.

一旦确定哪个尺寸与边界框相等,就可以使用图像的纵横比来计算其他尺寸.

double sourceRatio = sourceImage.Width / sourceImage.Height;
double targetRatio = targetRect.Width / targetRect.Height;

Size finalSize;
if (sourceRatio > targetRatio)
{
    finalSize = new Size(targetRect.Width, targetRect.Width / sourceRatio);
}
else
{
    finalSize = new Size(targetRect.Height * sourceRatio, targetRect.Height);
}
Run Code Online (Sandbox Code Playgroud)