2010-10-27 73 views
2

我使用这个类来上传图像并调整图像大小。问题是图像质量差!我需要上传图像而不会丢失质量!上传图像不失质量

class SimpleImage { 

    var $image; 
    var $image_type; 

    function load($filename) { 
     $image_info = getimagesize($filename); 
     $this->image_type = $image_info[2]; 
     if($this->image_type == IMAGETYPE_JPEG) { 
     $this->image = imagecreatefromjpeg($filename); 
     } elseif($this->image_type == IMAGETYPE_GIF) { 
     $this->image = imagecreatefromgif($filename); 
     } elseif($this->image_type == IMAGETYPE_PNG) { 
     $this->image = imagecreatefrompng($filename); 
     }  
    } 

    function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) { 
     if($image_type == IMAGETYPE_JPEG) { 
     imagejpeg($this->image,$filename,$compression); 
     } elseif($image_type == IMAGETYPE_GIF) { 
     imagegif($this->image,$filename);   
     } elseif($image_type == IMAGETYPE_PNG) { 
     imagepng($this->image,$filename); 
     } 
     if($permissions != null) { 
     chmod($filename,$permissions); 
     } 
    } 
    function output($image_type=IMAGETYPE_JPEG) { 
     if($image_type == IMAGETYPE_JPEG) { 
     imagejpeg($this->image); 
     } elseif($image_type == IMAGETYPE_GIF) { 
     imagegif($this->image);   
     } elseif($image_type == IMAGETYPE_PNG) { 
     imagepng($this->image); 
     } 
    } 

    function getWidth() { 
     return imagesx($this->image); 
    } 

    function getHeight() { 
     return imagesy($this->image); 
    } 

    function resizeToHeight($height) { 
     $ratio = $height/$this->getHeight(); 
     $width = $this->getWidth() * $ratio; 
     $this->resize($width,$height); 
    } 

    function resizeToWidth($width) { 
     $ratio = $width/$this->getWidth(); 
     $height = $this->getheight() * $ratio; 
     $this->resize($width,$height); 
    } 

    function scale($scale) { 
     $width = $this->getWidth() * $scale/100; 
     $height = $this->getheight() * $scale/100; 
     $this->resize($width,$height); 
    } 

    function resize($width,$height) { 
     $new_image = imagecreatetruecolor($width, $height); 
     imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); 
     $this->image = $new_image; 
    }  
} 

任何人都可以请帮忙吗?

+0

质量问题已得到解决,但还有一个问题。当我上传透明PNG图像时,透明部分变黑。这怎么能修复? – 2010-10-27 14:43:52

+0

参见例如这里:http://stackoverflow.com/questions/313070/png-transparency-with-php – mercator 2010-10-27 14:57:51

回答

4

我看到75作为$compression参数的默认值。您将其作为imagejpeg的质量参数传递。这可能会导致质量损失。

7

一两件事你可以做的是,当你调用的功能保存,

改变质量参数从75到100,当你调用imagejpeg

质量是可选的,从0(最严重的质量范围,小文件)为100(最好的质量,最大的文件)。默认值是默认的IJG质量值(约75)。

+0

注意'imagepng',因为它的数字从'9 - 0'(是的,倒退)。 – 2010-10-27 14:27:21

+0

我认为完美形象90,但经常使用85可接受的价值。 – nerkn 2010-10-27 14:28:06

0

您保存功能默认质量值为75.因此,无论是将其调到100还是将默认值更改为100,都要进行更改。100是最佳质量。