Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get image aspect ratio [duplicate]

Tags:

php

I'm currently trying to get the aspect ratio of an image using PHP. For example, using those values :

$thumb_width = 912;
$thumb_height = 608;

I would be able to get the aspect ratio (16:9, 3:2, 2:3, etc.). So in this case :

$ratio = '3:2';

The thing is: I don't know what new width or height it will be. so I can't do something like that : (original height / original width) x new width = new height

Any ideas ?

Note: I don't want to resize an image, just calculate its aspect ratio with its width and height.

like image 566
enguerranws Avatar asked Apr 15 '16 08:04

enguerranws


2 Answers

So you need to get the size of an image

http://php.net/manual/en/function.getimagesize.php

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

so here you have $width and $height ready

Then you can use this answer here https://stackoverflow.com/a/9143510/953684 to convert the result of $width/$height to a ratio.

like image 196
Sharky Avatar answered Oct 07 '22 14:10

Sharky


I always prefer the most compact solution in coding. They're mostly faster, more robust and better to read.

While the option that is mentioned by @Sharky in the accepted answer will probably do the job, i think the following solution is much more elegant and definitely better readable:

$imageWidth = 912;
$imageHeight = 608;

$divisor = gmp_intval( gmp_gcd( $imageWidth, $imageHeight ) );
$aspectRatio = $imageWidth / $divisor . ':' . $imageHeight / $divisor;

More information about the functions in the PHP manual for gmp_intval and gmp_gcd.

like image 44
GDY Avatar answered Oct 07 '22 16:10

GDY