Reputation: 3841
I need an algorithm that given an image's width, height and a target ratio will calculate the number of pixels to be shaved from the image's sides to get to that ratio, that has the smallest change in the image's area.
How might one implement such an algorithm?
Edit
Sorry for the inconsistency in my original question; I have revised my it.
Upvotes: 5
Views: 2755
Reputation: 10579
To minimize the change in area, you want to find the largest rectangle of the desired aspect ratio that will fit inside the original image bounds.
So, if the original image is too wide, then make the final image's height = original height, and shave off the extra width.
If the original image is too tall, make the final image's width = original width, and shave off the extra height.
Note: This assumes that you are not allowed to increase the width or height beyond the original dimensions. If that is not the case, the algorithm would be:
Constraint 1: x_final * y_final = x_initial * y_initial
Contraint 2: x_final / y_final = r
The solution is:
x_final = sqrt(r*x_initial*y_initial)
y_final = sqrt(x_initial*y_initial/r)
Upvotes: 0
Reputation: 51531
Upvotes: 6