Scale Image Using PHP and Maintaining Aspect Ratio

前端 未结 10 1994
孤独总比滥情好
孤独总比滥情好 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:25

    I found a mathematical way to get this job done

    Github repo - https://github.com/gayanSandamal/easy-php-image-resizer

    Live example - https://plugins.nayague.com/easy-php-image-resizer/

     $after_width) {
    
        //get the reduced width
        $reduced_width = ($width - $after_width);
        //now convert the reduced width to a percentage and round it to 2 decimal places
        $reduced_radio = round(($reduced_width / $width) * 100, 2);
    
        //ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places
        $reduced_height = round(($height / 100) * $reduced_radio, 2);
        //reduce the calculated height from the original height
        $after_height = $height - $reduced_height;
    
        //Now detect the file extension
        //if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG'
        if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'JPEG') {
            //then return the image as a jpeg image for the next step
            $img = imagecreatefromjpeg($source_url);
        } elseif ($extension == 'png' || $extension == 'PNG') {
            //then return the image as a png image for the next step
            $img = imagecreatefrompng($source_url);
        } else {
            //show an error message if the file extension is not available
            echo 'image extension is not supporting';
        }
    
        //HERE YOU GO :)
        //Let's do the resize thing
        //imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]);
        $imgResized = imagescale($img, $after_width, $after_height, $quality);
    
        //now save the resized image with a suffix called "-resized" and with its extension. 
        imagejpeg($imgResized, $filename . '-resized.'.$extension);
    
        //Finally frees any memory associated with image
        //**NOTE THAT THIS WONT DELETE THE IMAGE
        imagedestroy($img);
        imagedestroy($imgResized);
    }
    ?>
    

提交回复
热议问题