<?php/** * 縮圖產生類,使用樣本: */$newimage=new ImageResize();$newimage->resize("1.jpg","1_lit.jpg",1000,1000);echo $newimage->GetLastError();class ImageResize{ private $localimage;//原圖路徑 private $remoteimage;//縮圖儲存路徑 private $localinfo;//原圖屬性 private $error; function resize($localimg, $remoteimg, $x, $y) { //檢測是否支援gd影像處理 if(!$this->_checkenv()){ return false; } $this->localimage = $localimg; $this->remoteimage = $remoteimg; $this->localinfo = getimagesize($this->localimage); //擷取本地映像的資訊 return $this->_resize($x,$y); } /** * 檢測當前環境是否支援GD */ private function _checkenv(){ if(!function_exists('gd_info')){ $this->error[]="當前環境不支援GD影像處理,請先安裝GD庫並開啟PHP相關擴充"; return false; } return true; } /** * 產生縮圖主函數 * @param int $x 指定的縮圖寬度 * @param int $y 指定的縮圖高度 * @return boolean */ private function _resize($x,$y){ if(!$this->localinfo){ $this->error[]="本地影像檔不存在"; return false; } //建立映像控制代碼 $im=@$this->_create($this->localinfo[2]); if(!$im){ $this->error[]="當前GD庫不支援映像類型:{$this->localinfo['mime']}"; return false; } $dstsize=$this->_dstsize($x, $y); $dstim=@imagecreatetruecolor($dstsize["width"],$dstsize["height"]); $whitecolor=@imagecolorallocatealpha($dstim, 0, 0, 0,127); imagefill($dstim,0,0,$whitecolor); $re=@imagecopyresampled($dstim, $im, 0, 0, 0, 0, $dstsize["width"], $dstsize["height"], $this->localinfo[0], $this->localinfo[1]); if(!$re){ $this->error[]="映像重新採樣失敗"; return false; } if(!imagejpeg($dstim, $this->remoteimage)){ if(!imagepng($dstim,$this->remoteimage)){ if(!imagegif($dstim,$this->remoteimage)){ $this->error[]="儲存縮圖到{$this->remoteimage}失敗,請檢查gd環境是否正常和縮圖檔案夾的寫入許可權。"; return false; } } } $this->error[]="success"; return true; } /** * 根據本地圖片類型,建立圖片資源 * @param 映像類型代碼 $code * @return resource/boolean 成功則返回resourse失敗則返回false */ private function _create($code){ $src=$this->localimage; switch ($code){ case 1: return imagecreatefromgif($src); break; case 2: return imagecreatefromjpeg($src); break; case 3: return imagecreatefrompng($src); break; default : return false; break; } } /** * 按比例計算合適的寬度 * @param int $x 指定的縮圖寬度 * @param int $y 指定的縮圖高度 * @return array 包含調整後的縮圖寬度和高度 */ private function _dstsize($x,$y){ list($srcwidth,$srcheight)=$this->localinfo; if(($srcwidth/$srcheight)<($x/$y)){ $x=floor($y*$srcwidth/$srcheight); }else{ $y=floor($x*$srcheight/$srcwidth); } $dstsize["width"]=$x; $dstsize["height"]=$y; return $dstsize; } /** * 擷取最後一條錯誤資訊 * return string */ function GetLastError(){ return array_pop($this->error); } /** * 擷取所有錯誤資訊 * return array */ function GetAllError(){ return $this->error; }}