Last active
January 13, 2025 17:10
-
-
Save wazum/5710d9ef064caac7b909a9e69867f53b to your computer and use it in GitHub Desktop.
PHP Calculate aspect ratio from width and height
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function getAspectRatio(int $width, int $height) | |
{ | |
// search for greatest common divisor | |
$greatestCommonDivisor = static function($width, $height) use (&$greatestCommonDivisor) { | |
return ($width % $height) ? $greatestCommonDivisor($height, $width % $height) : $height; | |
}; | |
$divisor = $greatestCommonDivisor($width, $height); | |
return $width / $divisor . ':' . $height / $divisor; | |
} | |
echo getAspectRatio(1280, 1024); | |
echo PHP_EOL; | |
echo getAspectRatio(1275, 715); |
This is a great solution. I was looking here but your answer was much better. I didn't want to post and take credit. Maybe you want to post an answer here?
https://stackoverflow.com/questions/36642512/get-image-aspect-ratio
Thanks for the solution 👍
useful just to add list($width, $height, $type, $attr) = getimagesize("path/to/your/image.jpg");
reference
@wazum Can I request to make another function which do reverse of the getAspectRatio
like it will provide height and width from the getAspectRatio
is there way to reverse this logic ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output