I want to write a function to downsize an image to fit specified bounds. For example i want to resize a 2000×2333 image to fit into 1280×800. 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;
}
And it seemed to work. Well … seemed. But then i tried to resize a 1280×1024 image to a 1280×800 bounds and it gave me a result of 1280×1024 (which obviously doesn’t fit in 1280×800).
Does anybody have any ideas how this algorithm 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.
After this shrink the image by the biggest ratio. For example, if you wanted to resize an 800×600 image into a 400×400 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 400×300 image.