Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

Scale Image Using PHP and Maintaining Aspect Ratio

Basically I want to upload an image (which i've sorted) and scale it down to certain constraints such as max width and height but maintain the aspect ratio of the original image.

I don't have Imagick installed on the server - otherwise this would be easy.

Any help is appreciated as always. Thanks.

EDIT: I don't need the whole code or anything, just a push in the right direction would be fantastic.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...