本文實例講述了php封裝的圖片(縮略圖)處理類。分享給大家供大家參考,具體如下:
<?php
//圖片處理工具類
class Image{
//屬性
private $thumb_width; //縮略圖的寬
private $thumb_height;
//錯誤屬性
public $thumb_error;
//構造方法
public function __construct($width = 0,$height = 0){
$this->thumb_width = ($width == 0) ? $GLOBALS['config']['admin_goods_thumb']['width'] : $width;
$this->thumb_height = ($height == 0) ? $GLOBALS['config']['admin_goods_thumb']['height'] : $height;
}
/*
* 制作縮略圖
* @param1 string $src,原圖路徑,/uploads/20150122101010abcdef.gif
* @param2 string $path,縮略圖保存路徑/uploads/thumb_20150122101010abcdef.gif
* @return 縮略圖的名字
*/
public function makeThumb($src,$path){
//判斷原圖是否存在
if(!file_exists($src)){
$this->thumb_error = '原圖不存在!';
return false;
}
//打開原圖資源
//獲取能夠使用的後綴
$ext = $this->getFunctionName($src); //gif
//拼湊函數名
$open = 'imagecreatefrom' . $ext; //imagecreatefromgif
$save = 'image' . $ext; //imagegif
//如果不清楚;echo $open,$save;exit;
//可變函數打開原圖資源
$src_img = $open($src); //利用可變函數打開圖片資源
//imagecreatefromgif($src)
//縮略圖資源
$dst_img = imagecreatetruecolor($this->thumb_width,$this->thumb_height);
//背景色填充白色
$dst_bg_color = imagecolorallocate($dst_img,255,255,255);
imagefill($dst_img,0,0,$dst_bg_color);
//寬高比確定寬高
$dst_size = $this->thumb_width / $this->thumb_height;
//獲取原圖數據
$file_info = getimagesize($src);
$src_size = $file_info[0]/$file_info[1];
//求出縮略圖寬和高
if($src_size > $dst_size){
//原圖寬高比大於縮略圖
$width = $this->thumb_width;
$height = round($width / $src_size);
}else{
$height = $this->thumb_height;
$width = round($height * $src_size);
}
//求出縮略圖起始位置
$dst_x = round($this->thumb_width - $width)/2;
$dst_y = round($this->thumb_height - $height)/2;
//制作縮略圖
if(imagecopyresampled($dst_img,$src_img,$dst_x,$dst_y,0,0,$width,$height,$file_info[0],$file_info[1])){
//采樣成功:保存,將文件保存到對應的路徑下
$thumb_name = 'thumb_' . basename($src);
$save($dst_img,$path . '/' . $thumb_name);
//保存成功
return $thumb_name;
}else{
//采樣失敗
$this->thumb_error = '縮略圖采樣失敗!';
return false;
}
}
/*
* 獲取文件要調用的函數名
* @param1 string $file,文件名字
* @return 通過文件後綴名得到的函數字符串
*/
private function getFunctionName($file){
//得到文件的後綴
$file_info = pathinfo($file);
$ext = $file_info['extension']; //後綴:gif,png,jpg,jpeg,pjpeg
//imagecreatefromgif,imagecreatefromjpeg,imagecreatefrompng
//定義一個數組保存函數名
$func = array(
'gif' => 'gif',
'png' => 'png',
'jpg' => 'jpeg',
'jpeg' => 'jpeg',
'pjpeg' => 'jpeg'
);
//返回值
return $func[$ext];
}
}
更多關於PHP相關內容感興趣的讀者可查看本站專題:《php文件操作總結》、《PHP圖形與圖片操作技巧匯總》、《PHP數組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php面向對象程序設計入門教程》、《PHP網絡編程技巧總結》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。