Jaume Mal
Jaume Mal

Reputation: 658

Given an aspect ratio, calculate an int width that will result in an int height

Given an image ratio such as 1.5001489425082, how to calculate the minimum possible width that is always an int, not a float, and that, respecting the ratio, results in a height that is always an int aswell ?

I am trying to create image placeholders on the fly and I came out with this code (uses kirby cms chain syntax, but pretty self-explanatory):

<img src="<?= $file->resize(10,(10/$file->ratio()))->url() ?>"

... I resize() the $file, using 10 as width, and (10/$file-ratio()) as height. But this sometimes results in floating point numbers, which won't do as we are working here with pixels.

Thus the question about being able to choose the minimum width that is an int, and that will result in a height that is also an int ALWAYS.

Thank you

Upvotes: 0

Views: 189

Answers (1)

Simon Goater
Simon Goater

Reputation: 1908

If an image has integer width and height, w and h respectively then being given only an approximate float value of their ratio is not enough information to reliably obtain the lowest integer width and height values you're looking for. If you know w and h, the they can be made as small as possible while keeping them both integers and maintaining the same ratio by dividing by their Greatest Common Divisor gcd(w,h).

Upvotes: 1

Related Questions