I'm currently trying to get the aspect ratio of an image using PHP. For example, using those values :
$thumb_width = 912;
$thumb_height = 608;
I would be able to get the aspect ratio (16:9, 3:2, 2:3, etc.). So in this case :
$ratio = '3:2';
The thing is: I don't know what new width or height it will be. so I can't do something like that : (original height / original width) x new width = new height
Any ideas ?
Note: I don't want to resize an image, just calculate its aspect ratio with its width and height.
So you need to get the size of an image
http://php.net/manual/en/function.getimagesize.php
list($width, $height, $type, $attr) = getimagesize("path/to/your/image.jpg");
so here you have $width
and $height
ready
Then you can use this answer here https://stackoverflow.com/a/9143510/953684 to convert the result of $width/$height
to a ratio.
I always prefer the most compact solution in coding. They're mostly faster, more robust and better to read.
While the option that is mentioned by @Sharky in the accepted answer will probably do the job, i think the following solution is much more elegant and definitely better readable:
$imageWidth = 912;
$imageHeight = 608;
$divisor = gmp_intval( gmp_gcd( $imageWidth, $imageHeight ) );
$aspectRatio = $imageWidth / $divisor . ':' . $imageHeight / $divisor;
More information about the functions in the PHP manual for gmp_intval and gmp_gcd.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With