Resize image in PHP

前端 未结 13 1842
长情又很酷
长情又很酷 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:50

    You need to use either PHP's ImageMagick or GD functions to work with images.

    With GD, for example, it's as simple as...

    function resize_image($file, $w, $h, $crop=FALSE) {
        list($width, $height) = getimagesize($file);
        $r = $width / $height;
        if ($crop) {
            if ($width > $height) {
                $width = ceil($width-($width*abs($r-$w/$h)));
            } else {
                $height = ceil($height-($height*abs($r-$w/$h)));
            }
            $newwidth = $w;
            $newheight = $h;
        } else {
            if ($w/$h > $r) {
                $newwidth = $h*$r;
                $newheight = $h;
            } else {
                $newheight = $w/$r;
                $newwidth = $w;
            }
        }
        $src = imagecreatefromjpeg($file);
        $dst = imagecreatetruecolor($newwidth, $newheight);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    
        return $dst;
    }
    

    And you could call this function, like so...

    $img = resize_image(‘/path/to/some/image.jpg’, 200, 200);
    

    From personal experience, GD's image resampling does dramatically reduce file size too, especially when resampling raw digital camera images.

提交回复
热议问题