在实际生产过程中,我们经常会遇到上传的图片于实际使用中图片比例不同的情况,对于很多老旧数据,我们也不可能重新去将所有的图片再传一遍,于是在图片的img标签中,如果能够按照我们的参数重新生成合适大小的缩略图,那么再好不过了。
于是我本着方便大家的原则,将我的项目按照以上的思路整理了一番,下面是我的源代码~[如果大家有更好的思路,欢迎指正点评~]
本文开启了评论权限
下面是源代码:
本源代码仅仅适合于tp5,tp5.1,tp6.0等,使用前请自行安装tp的图片处理类
/**
* 根据传来的函数 生成合适的缩略图
* @param $path
* @param int $width
* @param int $height
* $type 1裁剪 ,2缩略
* @return string
*/
function img_thumber($path,$width=150,$height=115,$type=1){
//return "/application/myclass/phpthumber/phpThumb.php?src={$path}&w={$width}&h={$height}";
$old_path = $path;
//去除域名
if (strstr($path,"http")){
$domain = request()->domain();
$start = strlen($domain);
$end = strlen($path);
$path = substr($path,$start,$end);
}
//判断原图路径 是否为图片 没有则新生成
/*if(is_file(".".$path)){
return $path;
}*/
//组个新图片的路径及名称
$arr = explode("/",$path);
$name = md5(end($arr));
array_pop($arr);
$arr[] = $name;
if(!$arr[0]){
unset($arr[0]);
}
$str = '';
foreach ( $arr as $k => $v){
$str .= "/".$v;
}
$suoluetu1_name = $str."_".$width."_".$height.".png";
if(is_file('.'.$suoluetu1_name)){
return $suoluetu1_name;
}
//$image->crop(300, 300)->save('./crop.png');
try{
$image = \think\Image::open('.'.$path);
$suoluetu1_name = ".".$suoluetu1_name;
if($type == 2){
$image->thumb($width, $height)->save($suoluetu1_name); //缩略
}
if($type == 1){
//居中裁剪
$image->thumb($width, $height,\think\Image::THUMB_CENTER)->save($suoluetu1_name);
}
//$image->crop(300, 300)->save('./crop.png');
$suoluetu1_name = substr($suoluetu1_name,1,strlen($suoluetu1_name));
}catch (Exception $exception){
$suoluetu1_name = $old_path;
}
return $suoluetu1_name;
}