Skip to content

Instantly share code, notes, and snippets.

@wazum
Last active October 26, 2023 13:41
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save wazum/5710d9ef064caac7b909a9e69867f53b to your computer and use it in GitHub Desktop.
Save wazum/5710d9ef064caac7b909a9e69867f53b to your computer and use it in GitHub Desktop.
PHP Calculate aspect ratio from width and height
<?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);
@wazum
Copy link
Author

wazum commented Oct 7, 2019

Output

5:4
255:143

@pdxbug
Copy link

pdxbug commented Jul 22, 2021

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

@felixranesberger
Copy link

Thanks for the solution 👍

@vrkansagara
Copy link

useful just to add list($width, $height, $type, $attr) = getimagesize("path/to/your/image.jpg"); reference

@vrkansagara
Copy link

@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