图像缩放算法 [英] Image resizing algorithm
问题描述
我想编写一个函数来缩小图像以适合指定的边界。比如我想调整一个2000x2333的图像,以适应1280×800。纵横比必须保持。我想出了下面的算法:
I want to write a function to downsize an image to fit specified bounds. For example i want to resize a 2000x2333 image to fit into 1280x800. The aspect ratio must be maintained. I've come up with the following algorithm:
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;
}
和它似乎工作。嗯......好像。但后来我试图调整大小1280×1024的图像为1280×800的边界,它给了我1280×1024的结果(这显然不适合在1280×800)。
And it seemed to work. Well ... seemed. But then i tried to resize a 1280x1024 image to a 1280x800 bounds and it gave me a result of 1280x1024 (which obviously doesn't fit in 1280x800).
任何人有任何想法,这algorighm应该如何工作?
Anyone has any ideas how this algorighm should work?
推荐答案
就是我通常做的是看原来的宽度和新的宽度和原来的高度和新的高度之间的比例之间的比率。
The way I usually do this is to look at the ratio between the original width and the new width and the ratio between the original height and the new height.
在这个缩小图像的最大比例。例如,如果你想调整800x600的图像转换成400×400图像的长宽比是2,高度比为1.5。以2的比率缩小图像给出400x300的图像。
After this shrink the image by the biggest ratio. For example, if you wanted to resize an 800x600 image into a 400x400 image the width ratio would be 2, and the height ratio would be 1.5. Shrinking the image by a ratio of 2 gives a 400x300 image.
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;
}
这篇关于图像缩放算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!