Resize image in PHP

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

    If you dont care about the aspect ration (i.e you want to force the image to a particular dimension), here is a simplified answer

    // for jpg 
    function resize_imagejpg($file, $w, $h) {
       list($width, $height) = getimagesize($file);
       $src = imagecreatefromjpeg($file);
       $dst = imagecreatetruecolor($w, $h);
       imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
       return $dst;
    }
    
     // for png
    function resize_imagepng($file, $w, $h) {
       list($width, $height) = getimagesize($file);
       $src = imagecreatefrompng($file);
       $dst = imagecreatetruecolor($w, $h);
       imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
       return $dst;
    }
    
    // for gif
    function resize_imagegif($file, $w, $h) {
       list($width, $height) = getimagesize($file);
       $src = imagecreatefromgif($file);
       $dst = imagecreatetruecolor($w, $h);
       imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
       return $dst;
    }
    

    Now let's handle the upload part. First step, upload the file to your desired directory. Then called one of the above functions based on file type (jpg, png or gif) and pass the absolute path of your uploaded file as below:

     // jpg  change the dimension 750, 450 to your desired values
     $img = resize_imagejpg('path/image.jpg', 750, 450);
    

    The return value $img is a resource object. We can save to a new location or override the original as below:

     // again for jpg
     imagejpeg($img, 'path/newimage.jpg');
    

    Hope this helps someone. Check these links for more on resizing Imagick::resizeImage and imagejpeg()

提交回复
热议问题