8

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.

enguerranws
  • 8,087
  • 8
  • 49
  • 97
  • 1
    Won't this help you: http://stackoverflow.com/questions/8044052/get-aspect-ratio-from-width-and-height-of-image-php-or-js?rq=1? – Gino Pane Apr 15 '16 at 09:17

2 Answers2

15

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.

Community
  • 1
  • 1
Sharky
  • 6,154
  • 3
  • 39
  • 72
3

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.

GDY
  • 2,872
  • 1
  • 24
  • 44