PHP等比例縮放圖片大小壓縮圖片空間
阿新 • • 發佈:2018-12-30
/**
* 等比例壓縮圖片,支援圖片格式jpg,jpeg,png
* @param string $dst_dir 上傳的資料夾
* @param string $dst_name 上傳後的名稱,不包括副檔名
* @param int $maxWidth 如果需要等比例壓縮圖片,指定壓縮後的最大寬度,預設為200
* @param int $maxHeight 如果需要等比例壓縮圖片,指定壓縮後的最大高度,預設為200
* @return boolean 成功返回true,否則返回false
*/
privatefunctionresize_image_and_keep_ratio(){
//設定描繪的x、y座標,高度、寬度
$dst_x=$dst_y=$src_x=$src_y=0;
$ratio=min($this->given_height/$this->original_info['height'],$this->given_width/$this->original_info['width']);
$dst_h=ceil($this->original_info['height']*$ratio);
$dst_w=ceil($this->original_info['width']*$ratio);
$dst_x=($this->given_width-$dst_w )/2;
$dst_y=($this->given_height-$dst_h)/2;
return$this->copy($this->given_width,$this->given_height,$dst_x,$dst_y,$src_x,$src_y,
$dst_w,$dst_h);
}
/**
* copy original image to new size
* @param int $dst_w
* @param int $dst_h
* @param int $dst_x
* @param int $dst_y
* @param int $src_x
* @param int $src_y
* @param int $draw_w
* @param int $draw_h
* @return boolean
*/
privatefunctioncopy($dst_w,$dst_h,$dst_x=0,$dst_y=0,$src_x=0,$src_y=0,$draw_w=0,$draw_h=0){
// Generate new GD image
$new=imagecreatetruecolor($dst_w,$dst_h);
$draw_w=$draw_w==0?$this->original_info['width']:$draw_w;
$draw_h=$draw_h==0?$this->original_info['height']:$draw_h;
if($this->original_info['format']==='gif'){
// Preserve transparency in GIFs
$transparent_index=imagecolortransparent($this->image);
$palletsize=imagecolorstotal($this->image);
if($transparent_index>=0&&$transparent_index<$palletsize){
$transparent_color=imagecolorsforindex($this->image,$transparent_index);
$transparent_index=imagecolorallocate($new,$transparent_color['red'],$transparent_color['green'],$transparent_color['blue']);
imagefill($new,0,0,$transparent_index);
imagecolortransparent($new,$transparent_index);
if(!empty($this->bgcolor)){
$bg=imagecolorallocate($new,$this->bgcolor[0],$this->bgcolor[1],$this->bgcolor[2]);
imagefill($new,0,0,$bg);
}
}
}else{
// Preserve transparency in PNGs (benign for JPEGs)
imagealphablending($new,false);
imagesavealpha($new,true);
$color=imagecolorallocatealpha($new,0,0,0,127);
imagefill($new,0,0,$color);
if(!empty($this->bgcolor)){
$bg=imagecolorallocate($new,$this->bgcolor[0],$this->bgcolor[1],$this->bgcolor[2]);
imagefill($new,0,0,$bg);
}
}
// Resize
$flag=imagecopyresampled($new,$this->image,$dst_x,$dst_y,$src_x,$src_y,$draw_w,$draw_h,
$this->original_info['width'],$this->original_info['height']);
if($flag){
$this->image=$new;
$this->original_info['width']=$dst_w;
$this->original_info['height']=$dst_h;
}else{
thrownew\Exception('copy image error');
}
return$flag;
}
呼叫:
圖形處理函式庫 |
http://www.t086.com/code/php/group.php-20.php