1. 程式人生 > >PHP將上傳圖片自動放縮到指定解析度,保持清晰度

PHP將上傳圖片自動放縮到指定解析度,保持清晰度

class AutoImage{
    private $image;

    public function resize($src, $width, $height){
        //$src 就是 $_FILES['upload_image_file']['tmp_name']
        //$width和$height是指定的解析度
        //如果想按指定比例放縮,可以將$width和$height改為$src的指定比例
        $this->image = $src;
        $info = getimagesize($src);//獲取圖片的真實寬、高、型別
        if($info[0] == $width && $info[1] == $height){
            //如果解析度一樣,直接返回原圖
            return $src;
        }
        switch ($info['mime']){
            case 'image/jpeg':
                header('Content-Type:image/jpeg');
                $image_wp = imagecreatetruecolor($width, $height);
                $image_src = imagecreatefromjpeg($src);
                imagecopyresampled($image_wp,  $image_src, 0, 0, 0, 0, $width, $height, $info[0], $info[1]);
                imagedestroy($image_src);
                imagejpeg($image_wp,$this->image);
                break;
            case 'image/png':
                header('Content-Type:image/png');
                $image_wp = imagecreatetruecolor($width, $height);
                $image_src = imagecreatefrompng($src);
                imagecopyresampled($image_wp, $image_src, 0, 0, 0, 0, $width, $height, $info[0], $info[1]);
                imagedestroy($image_src);
                imagejpeg($image_wp,$this->image);
                break;
            case 'image/gif':
                header('Content-Type:image/gif');
                $image_wp = imagecreatetruecolor($width, $height);
                $image_src = imagecreatefromgif($src);
                imagecopyresampled($image_wp, $image_src, 0, 0, 0, 0, $width, $height, $info[0], $info[1]);
                imagedestroy($image_src);
                imagejpeg($image_wp,$this->image);
                break;

        }

        return $this->image;

    }
}