moteutsch
moteutsch

Reputation: 3841

Algorithm for cropping image to specific ratio

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

Answers (2)

mbeckish
mbeckish

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

Svante
Svante

Reputation: 51531

  1. Bring the ratio into reduced form, so that gcd(ratio_width, ratio_height) = 1.
  2. Calculate floor(width / ratio_width) and floor(height / ratio_height). Your factor is the minimum of these two.
  3. Multiply ratio_width and ratio_height by that factor to obtain the new image dimensions.
  4. Shave the difference.

Upvotes: 6

Related Questions