php 缩略图封装的方法

/**
* PHP生成缩略图
* @param $basepath /原文件地址
* @param $des_w /缩略图的宽
* @param $des_h /缩略图的高
* @param $style /规则名称
* @param $line /连接符
* @param int $save / 展示方式 0展示缩略图(默认) 1保存缩略图
* @return string
*/
function thumb($basepath, $des_w, $des_h, $style, $line, $save = 0)
{
if(!file_exists($basepath)) {
return 'file not exists';
}
$fileExt = substr(basename($basepath), strrpos(basename($basepath), '.'));
$file = basename(basename($basepath), $fileExt);
$fileinfo = getimagesize($basepath);
$src_w = $fileinfo[0];
$src_h = $fileinfo[1];
$type = $fileinfo[2];
$type_array = [1=> 'gif', 2=> 'jpeg', 3=> 'png'];
$type_str = $type_array[$type];//jpeg

$fun_str = 'imagecreatefrom';
$function = $fun_str.$type_str;//imagecreatefromjpeg
//原图片资源
$src_img = $function($basepath);

$srcAvg = round($src_w / $src_h, 1);
if($des_h == 0 && $des_w != 0) {
//固定宽
$des_width = $des_w;
$des_height = round($des_w / $srcAvg);
} elseif ($des_w == 0 && $des_h != 0) {
//固定高
$des_height = $des_h;
$des_width = round($des_height * $srcAvg);
} elseif ($des_w == 0 && $des_h == 0) {
//原图
$des_width = $src_w;
$des_height = $src_h;
} elseif ($des_w != 0 && $des_h != 0) {
$des_width = $des_w;
$des_height = $des_h;
}
$des_img = imagecreatetruecolor($des_width, $des_height);
imagecopyresampled($des_img, $src_img, 0, 0, 0, 0, $des_width, $des_height, $src_w, $src_h);

$thumb = 'image'.$type_str;//imagejpeg
if($save) {
//保存缩略图
$filename = dirname($basepath) . '/' . $file.$line.$style.$fileExt;//保存
$thumb($des_img, $filename);
} else {
header('Content-type: image/'. $type_str .'');
$thumb($des_img);//展示图片
}
imagedestroy($des_img);
imagedestroy($src_img);
if($save) {
return $filename;
} else {
return true;
}
}
原文地址:https://www.cnblogs.com/l-zl/p/7263416.html