Scale Image Using PHP and Maintaining Aspect Ratio

前端 未结 10 1977
孤独总比滥情好
孤独总比滥情好 2020-11-30 07:38

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

10条回答
  •  春和景丽
    2020-11-30 08:24

    I know you are looking for a divisor that will allow resize your image proportionally. Check this demo

    How to get our divisor mathematically

    lets assume our original image has width x and height y; x=300 and y = 700

    Maximum height and maximum width is 200;

    First, we will check which dimension of the image is greater than the other. Our height (y) is greater than width(x)

    Secondly, we check if our height is greater than our maximum height. For our case, our height is greater than the maximum height. In a case where it less that the maximum height, we set our new height to our original height.

    Finally, we look for our divisor as shown below

    if y is set to maximum height 200 and max-y=200;
    y=max-y, that is 
    if y=max-y
    what about 
    x=?
    that is, 
    if 700 is resized to 200
    what about 300?
    700=200
    300=?
    new width = (200 (new height) * 300(width)) / 700 (height)
    so our divisor is
    divisor= new height (300) / height(700) 
    new width = divisor * width or width / (1/divisor)
    

    and vice versa for the width if it greater than height

    if ($width > $height) {
        if($width < $max_width)
            $newwidth = $width;
    
        else
    
        $newwidth = $max_width; 
    
    
        $divisor = $width / $newwidth;
        $newheight = floor( $height / $divisor);
    }
    else {
    
         if($height < $max_height)
             $newheight = $height;
         else
             $newheight =  $max_height;
    
        $divisor = $height / $newheight;
        $newwidth = floor( $width / $divisor );
    }
    

    See the full example and try it using the working demo .

提交回复
热议问题