<?php
class ImageLib{
private $error;
public function getError(){
return $this->error;
}
/*
* 製作縮略圖
* @param $src_path string 源圖的路徑
* @param $max_w int 畫布的寬度
* @param $max_h int 畫布的高度
* @param $flag bool 是否等比
* @param $prefix string 縮略圖的前綴
*/
public function thumb($src_path,$max_w,$max_h,$prefix='s_',$flag=false){
$ext= strtolower(strrchr($src_path,'.')); //獲取文件的後綴
switch($ext){
case '.jpg':
$type='jpeg';
break;
case '.gif':
$type='gif';
break;
case '.png':
$type='png';
break;
default:
$this->error='文件格式不正確';
return false;
}
$open_fn='imagecreatefrom'.$type; //拼接打開圖片的函數
$src=$open_fn($src_path); //打開源圖
$dst=imagecreatetruecolor($max_w,$max_h); //創建目標圖
$src_w=imagesx($src); //源圖的寬度
$src_h=imagesy($src); //源圖的高度
if($flag){ //等比縮放
if($max_w/$max_h<$src_w/$src_h){
$dst_w=$max_w;
$dst_h=$max_w*$src_h/$src_w;
}else {
$dst_h=$max_h;
$dst_w=$max_h*$src_w/$src_h;
}
//在目標圖上顯示的位置
$dst_x=(int)(($max_w-$dst_w)/2);
$dst_y=(int)(($max_h-$dst_h)/2);
}else{ //不等比
$dst_x=0;
$dst_y=0;
$dst_w=$max_w;
$dst_h=$max_h;
}
//生成縮略圖
imagecopyresampled($dst,$src,$dst_x,$dst_y,0,0,$dst_w,$dst_h,$src_w,$src_h);
$filename=basename($src_path); //文件名稱
$foldername=substr(dirname($src_path),-10); //文件夾名
$thumb_path=$GLOBALS['config']['app']['upload_path'].$foldername.DS.$prefix.$filename;//保存路徑
imagepng($dst,$thumb_path);
imagedestroy($dst);
imagedestroy($src);
return $foldername.'/'.$prefix.$filename;
}
}
php 縮略圖封裝類 製作縮略圖
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.