Scale Image Using PHP and Maintaining Aspect Ratio

Actually the accepted solution it is not the correct solution. The reason is simple: there will be cases when the ratio of the source image and the ratio of the destination image will be different. Any calculation should reflect this difference.

Please note the relevant lines from the example given on PHP.net website:

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
   $width = $height*$ratio_orig;
} else {
   $height = $width/$ratio_orig;
}

The full example may be found here:
http://php.net/manual/en/function.imagecopyresampled.php

There are other answers (with examples) on stackoverflow to similar questions (the same question formulated in a different manner) that suffer of the same problem.

Example:

Let’s say we have an image of 1630 x 2400 pixels that we want to be auto resized keeping the aspect ratio to 160 x 240. Let’s do some math taking the accepted solution:

if($old_x < $old_y) 
    {
        $thumb_w    =   $old_x*($new_width/$old_y);
        $thumb_h    =   $new_height;
    }

height = 240
width = 1630 * ( 160/2400 ) = 1630 * 0.0666666666666667 = 108.6666666666667
108.6 x 240 it’s not the correct solution.

The next solution proposed is the following:

if($old_x < $old_y)
    {
        $thumb_w    =   $old_x/$old_y*$newHeight;
        $thumb_h    =   $newHeight;
    }

height = 240;
width = 1630 / 2400 * 240 = 163
It is better (as it maintain the aspect ratio), but it exceeded the maximum accepted width.

Both fail.

We do the math according to the solution proposed by PHP.net:
width = 160
height = 160/(1630 / 2400) = 160/0.6791666666666667 = 235.5828220858896 (the else clause). 160 x 236 (rounded) is the correct answer.

Leave a Comment