Image resizing algorithm

I want to write a function to reduce the image size in accordance with the specified boundaries. For example, I want to resize a 2000x2333 image to insert into 1280x800. Aspect ratio should be maintained. I came 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 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 ... it seemed. But then I tried to change the image size of 1280x1024 to the border of 1280x800, and this gave me the result of 1280x1024 (which clearly does not correspond to 1280x800).

Anyone have any ideas how this algorithm should work?

+7
algorithm image resize
source share
2 answers

I usually do this to see the relationship between the original width and the new width and the ratio between the original height and the new height.

After that, the image will be reduced by the highest ratio. For example, if you want to resize an image from 800x600 to an image of 400x400, the width factor will be 2, and the height ratio will be 1.5. Reducing the image by a factor of 2 gives an image of 400 ร— 300.

 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 bounds float rh = mysize.height / height; if (rw > rh) { newh = round(mysize.height / rw); neww = width; } else { neww = round(mysize.width / rh); newh = height; } 
+26
source share

Here you can approach the problem:

You know that the height or width of the image will be equal to the width of the frame.

Once you determine which dimension is equal to the bounding box, you use the aspect ratio of the image to calculate another dimension.

 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); } 
+6
source share

All Articles