PHP基于GD庫的縮略圖生成,支持jpg,gif,png格式
<?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;
}
}</pre>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!