Calculate image aspect ratio in PHP

Calculating image aspect ratio in PHP is very simple. First you need to find greatest common divisor(GCD). You can do that by using following function:

function GCD($a, $b) {
while ($b != 0)
$remainder = $a % $b;
$a = $b;
$b = $remainder;
}
return abs ($a);
}

If you compiled your PHP version with GMP functions, you can also use following:

$gcd = gmp_gcd($a, $b);

After finding GCD, simply divide both sides with it:

$a = 2048; // screen width
$b = 1152; // screen height
$gcd = GCD($a, $b);
$a = $a/$gcd;
$b = $b/$gcd;
$ratio = $a . ":" . $b;

Post to Twitter Tweet This Post

One Comment

  1. messenger says:

    Thanks for this! I must admit I was very puzzled how to do this

Leave a Reply