PHP 按一定比例压缩图片,保持清晰度

159 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

大家好,感谢大家的持续关注,技术持续分享,工作难题和思路解决我都会分享,大家记得关注我!

微信关注公众号:倒腾怪,公众号内会持续分享优秀软件和技术文章,一定要关注哦~

好了,我们现在开始进入主题吧!今天给大家分享的是一个能够对图片进行压缩,并且保持清晰度,不会失真的类

在做头像或者将图片控制在一定范围内的场景中,都可以使用以下的类库对图片进行调整。

这里记录一下日常,也是分享给大家,有需要的朋友直接拿去用即可。

具体的类库和使用方法都在下面给出了实例,供大家参考,如有不足,直接在基础上进行修改即可

类库代码:


<?php  
/** 
 图片压缩操作类 
 v1.0 
*/  
   class Image{  
         
       private $src;  
       private $imageinfo;  
       private $image;  
       public  $percent = 0.1;  
       public function __construct($src){  
             
           $this->src = $src;  
             
       }  
       /** 
       打开图片 
       */  
       public function openImage(){  
             
           list($width, $height, $type, $attr) = getimagesize($this->src);  
           $this->imageinfo = array(  
                  
                'width'=>$width,  
                'height'=>$height,  
                'type'=>image_type_to_extension($type,false),  
                'attr'=>$attr  
           );  
           $fun = "imagecreatefrom".$this->imageinfo['type'];  
           $this->image = $fun($this->src);  
       }  
       /** 
       操作图片 
       */  
       public function thumpImage(){  
             
            $new_width = $this->imageinfo['width'] * $this->percent;  
            $new_height = $this->imageinfo['height'] * $this->percent;  
            $image_thump = imagecreatetruecolor($new_width,$new_height);  
            //将原图复制带图片载体上面,并且按照一定比例压缩,极大的保持了清晰度  
            imagecopyresampled($image_thump,$this->image,0,0,0,0,$new_width,$new_height,$this->imageinfo['width'],$this->imageinfo['height']);  
            imagedestroy($this->image);    
            $this->image =   $image_thump;  
       }  
       /** 
       输出图片 
       */  
       public function showImage(){  
             
            header('Content-Type: image/'.$this->imageinfo['type']);  
            $funcs = "image".$this->imageinfo['type'];  
            $funcs($this->image);  
             
       }  
       /** 
       保存图片到硬盘 
       */  
       public function saveImage($name){  
             
            $funcs = "image".$this->imageinfo['type'];  
            $funcs($this->image,$name.'.'.$this->imageinfo['type']);  
             
       }  
       /** 
       销毁图片 
       */  
       public function __destruct(){  
             
           imagedestroy($this->image);  
       }  
         
   }  
   
  
?> 

调用方式如下:

<?php  
          
        require 'image.class.php';  
        $src = "001.jpg";  
        $image = new Image($src);  
        $image->percent = 0.2;  
        $image->openImage();  
        $image->thumpImage();  
        $image->showImage();  
        $image->saveImage(md5("aa123"));  
  
  
?>  

以上就是今天的所有内容了,感谢大家的观看!记得关注昂~