开发者

Algorithm for cropping image to specific ratio

开发者 https://www.devze.com 2023-04-05 01:22 出处:网络
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

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 incon开发者_开发百科sistency in my original question; I have revised my it.


  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.


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消