我想编写一个函数来缩小图像以适应指定的边界。例如,我想调整 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;
}
它似乎奏效了。好吧……似乎。但是后来我尝试将 1280x1024 图像的大小调整为 1280x800 的边界,它给了我 1280x1024 的结果(这显然不适合 1280x800)。
有人知道这个算法应该如何工作吗?
最佳答案
我通常的做法是看原来的宽度和新的宽度的比例,以及原来的高度和新的高度的比例。
在此之后按最大比例缩小图像。例如,如果您想将 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;
}
关于algorithm - 图像调整算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3332237/