Resize image in PHP

前端 未结 13 1903
长情又很酷
长情又很酷 2020-11-22 04:18

I\'m wanting to write some PHP code which automatically resizes any image uploaded via a form to 147x147px, but I have no idea how to go about it (I\'m a relative PHP novice

13条回答
  •  佛祖请我去吃肉
    2020-11-22 04:59

    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);
    }
    ?>
    

提交回复
热议问题