<?php //縮略圖類 class Thumb{ public static $thumb_prefix = '';//縮略圖前綴 public static $thumb_savePath = '';//縮略圖保存路徑 public static $thumb_width = '';//縮略圖寬度 public static $thumb_height = '';//縮略圖高度 public static function save($sPath){//保存爲縮略圖,傳入一個實參 $imgArr = self::getImageInfo($sPath);//獲取圖片信息 if (is_array($imgArr)) { //將三個靜態屬性以逗號爲分隔拆分爲數組,實現多張縮略圖的生成 $thumb_prefix_arr = explode(',', self::$thumb_prefix); $thumb_width_arr = explode(',', self::$thumb_width); $thumb_height_arr = explode(',', self::$thumb_height); $countP = count($thumb_prefix_arr); $countW = count($thumb_width_arr); $countH = count($thumb_height_arr); if ($countP>0 && $countP==$countW && $countW==$countH) { //遍歷一個數組,生成多張縮略圖 $reArr = array(); foreach ($thumb_prefix_arr as $key=>$value){ //生成空白畫布並填充顏色 $image = imagecreatetruecolor($thumb_width_arr[$key], $thumb_height_arr[$key]); $color = imagecolorallocate($image, 255, 255, 255);//白色 imagefill($image, 0, 0, $color); //計算出縮略比例 $width_scale = $imgArr['width']/$thumb_width_arr[$key];//寬比 $height_scale = $imgArr["height"]/$thumb_height_arr[$key];//高比 $scale = $width_scale>$height_scale ? $width_scale : $height_scale; //計算縮略圖寬高 $width = $imgArr["width"]/$scale; $height = $imgArr["height"]/$scale; //到目標圖片的位置 $dst_x = ($thumb_width_arr[$key]-$width)/2; $dst_y = ($thumb_height_arr[$key]-$height)/2; //獲取原始圖片資源並拷貝 $src_image = $imgArr["createFunName"]($sPath);//獲取原始圖片資源 imagecopyresized($image, $src_image, $dst_x, $dst_y, 0, 0, $width, $height, $imgArr["width"], $imgArr["height"]); //保存並返回值 $re = $imgArr['saveFunName']($image,self::$thumb_savePath.'/'.$thumb_prefix_arr[$key].$imgArr['name']); $reArr[$key] = $re; } //銷燬縮略圖資源及原圖片資源,釋放內存 imagedestroy($image); imagedestroy($src_image); return $reArr;//返回數組 }else{ return false; } }else{ return false; } } protected static function getImageInfo($path){ if (is_file($path)) { $imgArr = getimagesize($path); if (is_array($imgArr)) {//若是$imgArr是一個數組,則說明$path是一個真實圖片 //判斷不一樣的圖片類型,使用變量函數,生成圖片資源:$createFunName,保存圖片資源:$saveFunName switch ($imgArr['mime']){ case 'image/jpeg': case 'image/pjpeg': $createFunName = 'imagecreatefromjpeg'; $saveFunName = 'imagejpeg'; break; case 'image/png': $createFunName = 'imagecreatefrompng'; $saveFunName = 'imagepng'; break; case 'image/gif': $createFunName = 'imagecreatefromgif'; $saveFunName = 'imagegif'; break; default: return false; } //獲取原圖片名稱 $oldName = pathinfo($path,PATHINFO_BASENAME); //返回圖片信息數組 return array( 'name'=>$oldName, 'type'=>$imgArr['mime'], 'width'=>$imgArr[0], 'height'=>$imgArr[1], 'createFunName'=>$createFunName, 'saveFunName'=>$saveFunName ); } }else{ return false; } } }