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

I canโ€™t believe that I canโ€™t find the formula for this. I am using a PHP script called SLIR to resize images. The script asks you to specify the aspect ratio for cropping. I would like to get the aspect ratio based on the width and height of the image given in the form that I allow users to enter these values. For example, if a user enters an image of 1024x768, I would get a 4: 3 aspect ratio. In my life I cannot find an example of a formula in PHP or Javascript that I can use to get aspect ratios based on knowing w, h and connecting the aspect ratio to the variable.

+4
source share
4 answers

You do not need to do any calculations.

Just because he says that aspect ratio does not mean that he should be one of a limited set of commonly used coefficients . It can be any pair of numbers separated by a colon.

Quote from the SLIR usage guide :

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

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

Or, more briefly:

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

Please note that they did not bother to reduce this to c3:2 .

So, just use the values โ€‹โ€‹entered by the user: 1024:768 .

If you want to be concise, calculate the largest common divisor by width and height and divide them both by this. This will reduce your 1024:768 to 4:3 .

+2
source

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

original width * new height / original height = new width,

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

Or if you just want the ratio:

original width / original height = ratio

+9
source

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

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

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); 
+6
source

Here's a much simpler alternative for the largest common dividers:

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

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

If your server has not been 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); } 
+2
source

Source: https://habr.com/ru/post/1380089/


All Articles