最近手上的項目頁面要顯示不少圖片,雖然用了jQuery的lazyload,可是效果並沒理想,滑動到一個區域還要比較長的時間圖片才徹底顯示出來。因而想着將上傳上去的900KB+壓縮備份一份縮略圖。
PHP壓縮圖片兩個步驟:
一、添加類php
//php生成縮略圖片的類 class ResizeImage{ public $type;//圖片類型 public $width;//實際寬度 public $height;//實際高度 public $resize_width;//改變後的寬度 public $resize_height;//改變後的高度 public $cut;//是否裁圖 public $srcimg;//源圖象 public $dstimg;//目標圖象地址 public $im;//臨時建立的圖象 public $quality;//圖片質量 public $img_array=array('jpg','png','gif'); //http://www.phpernote.com/php-function/782.html function __construct($img,$wid,$hei,$c,$dstpath,$quality=100){ $this->srcimg=$img; $this->resize_width=$wid; $this->resize_height=$hei; $this->cut=$c; $this->quality=$quality; //$this->type=strtolower(substr(strrchr($this->srcimg,'.'),1));//圖片的類型 $this->type=$this->checkFileType($this->srcimg);//更爲嚴格的檢測圖片類型 if(!in_array($this->type,$this->img_array)){ return ''; } $this->initi_img();//初始化圖象 $this -> dst_img($dstpath);//目標圖象地址 $this->width=imagesx($this->im); $this->height=imagesy($this->im); $this->newimg();//生成圖象 ImageDestroy($this->im); } function newimg(){ $resize_ratio=($this->resize_width)/($this->resize_height);//改變後的圖象的比例 $ratio=($this->width)/($this->height);//實際圖象的比例 if(($this->cut)=='1'){//裁圖 if(function_exists('imagepng')&&(str_replace('.','',PHP_VERSION)>=512)){//針對php版本大於5.12參數變化後的處理狀況 $quality=9; } if($ratio>=$resize_ratio){//高度優先 $newimg=imagecreatetruecolor($this->resize_width,$this->resize_height); //上色 $color=imagecolorallocate($newimg,255,255,255); //設置透明 imagecolortransparent($newimg,$color); imagefill($newimg,0,0,$color); imagecopyresampled($newimg,$this->im,0,0,0,0,$this->resize_width,$this->resize_height,(($this->height)*$resize_ratio),$this->height); imagejpeg($newimg,$this->dstimg,$this->quality); } if($ratio<$resize_ratio){//寬度優先 $newimg=imagecreatetruecolor($this->resize_width,$this->resize_height); //上色 $color=imagecolorallocate($newimg,255,255,255); //設置透明 imagecolortransparent($newimg,$color); imagefill($newimg,0,0,$color); imagecopyresampled($newimg,$this->im,0,0,0,0,$this->resize_width,$this->resize_height,$this->width,(($this->width)/$resize_ratio)); imagejpeg($newimg,$this->dstimg,$this->quality); } }else{//不裁圖 if($ratio>=$resize_ratio){ $newimg=imagecreatetruecolor($this->resize_width,($this->resize_width)/$ratio);