Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get aspect ratio from width and height of image (PHP or JS)

I can't believe I can't find the formula for this. I am using a PHP script called SLIR to resize images. The script asks to specify an aspect ratio for cropping. I'd like to get the aspect ratio based on the width and height of the image being specified in a form I'm letting users enter these values in. For example, if a user enters a 1024x768 image, I would get an aspect ratio of 4:3. For the life of me, I can't find an example of the formula in PHP or Javascript I can use to get the aspect ratio values based on knowing the w,h and plug the aspect ratio into a variable.

like image 742
David Paul Albert Avatar asked Nov 30 '22 03:11

David Paul Albert


2 Answers

to get the aspect ratio just simplify the width and height like a fraction for example:

1024      4
----  =  ---
768       3

the php code:

function gcd($a, $b)
{
    if ($a == 0 || $b == 0)
        return abs( max(abs($a), abs($b)) );

    $r = $a % $b;
    return ($r != 0) ?
        gcd($b, $r) :
        abs($b);
}

  $gcd=gcd(1024,768);

  echo "Aspect ratio = ". (1024/$gcd) . ":" . (768/$gcd);
like image 37
user962284 Avatar answered Dec 18 '22 14:12

user962284


If you can get one of: height, width then you can calculate the missing width height:

original width * new height / original height = new width;

original height * new width / original width = new height;

Or if you just want a ratio:

original width / original height = ratio

like image 189
David Nguyen Avatar answered Dec 18 '22 14:12

David Nguyen