Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for cropping image to specific ratio

Tags:

algorithm

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.

like image 388
moteutsch Avatar asked Sep 13 '11 12:09

moteutsch


1 Answers

  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.
like image 136
Svante Avatar answered Sep 30 '22 14:09

Svante