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

一个人想着一个人 提交于 2019-11-30 10:09:17

There is no need for you to do any kind of calculation.

Just because it says aspect ratio doesn't mean it has to be one of a limited set of commonly used ratios. It can be any pair of numbers separated by a colon.

Quoting from the SLIR usage guide:

For example, if you want your image to be exactly 150 pixels wide by 100 pixels high, you could do this:

<img src="/slir/w150-h100-c150:100/path/to/image.jpg" alt="Don't forget your alt text" /> 

Or, more concisely:

<img src="/slir/w150-h100-c15:10/path/to/image.jpg" alt="Don't forget your alt text" />

Note that they didn't bother to reduce that even further to c3:2.

So, simply use the values as entered by the user: 1024:768.

If you want to be concise, calculate the greatest common divisor of the width and height and divide both of them by that. That would reduce your 1024:768 down to 4:3.

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

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);

Here's a much simpler alternative for greatest common divisor integer ratios:

function ratio( $x, $y ){
    $gcd = gmp_strval(gmp_gcd($x, $y));
    return ($x/$gcd).':'.($y/$gcd);
}

The request echo ratio(25,5); returns 5:1.

If your server wasn't compiled with GMP functions ...

function gcd( $a, $b ){
    return ($a % $b) ? gcd($b,$a % $b) : $b;
}
function ratio( $x, $y ){
    $gcd = gcd($x, $y);
    return ($x/$gcd).':'.($y/$gcd);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!