Resize images with PHP, support PNG, JPG

前端 未结 7 1400
囚心锁ツ
囚心锁ツ 2020-12-08 01:37

I am using this class:

class ImgResizer {

function ImgResizer($originalFile = \'$newName\') {
    $this -> originalFile = $originalFile;
}
function resiz         


        
7条回答
  •  爱一瞬间的悲伤
    2020-12-08 02:03

    You can try this. Currently it's assuming the image will always be a jpeg. This will allow you to load a jpeg, png, or gif. I haven't tested but it should work.

    function resize($newWidth, $targetFile) {
        if (empty($newWidth) || empty($targetFile)) {
            return false;
        }
    
        $fileHandle = @fopen($this->originalFile, 'r');
    
        //error loading file
        if(!$fileHandle) {
            return false;
        }
    
        $src = imagecreatefromstring(stream_get_contents($fileHandle));
    
        fclose($fileHandle);
    
        //error with loading file as image resource
        if(!$src) {
            return false;
        }
    
        //get image size from $src handle
        list($width, $height) = array(imagesx($src), imagesy($src));
    
        $newHeight = ($height / $width) * $newWidth;
    
        $tmp = imagecreatetruecolor($newWidth, $newHeight);
    
        imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    
        //allow transparency for pngs
        imagealphablending($tmp, false);
        imagesavealpha($tmp, true);
    
        if (file_exists($targetFile)) {
            unlink($targetFile);
        }
    
        //handle different image types.
        //imagepng() uses quality 0-9
        switch(strtolower(pathinfo($this->originalFile, PATHINFO_EXTENSION))) {
            case 'jpg':
            case 'jpeg':
                imagejpeg($tmp, $targetFile, 95);
                break;
            case 'png':
                imagepng($tmp, $targetFile, 8.5);
                break;
            case 'gif':
                imagegif($tmp, $targetFile);
                break;
        }
    
        //destroy image resources
        imagedestroy($tmp);
        imagedestroy($src);
    }
    

提交回复
热议问题