tp5动态生成缩略图函数、控制器
可以做成函数方法或通过控制器来做
1 函数方法
/* 生成缩略图 $dir 图片地址 $x 图片宽度 $y 图片高度 $y 图片高度 $cut 裁剪方式: 1标识缩略图等比例缩放类型, 2标识缩略图缩放后填充类型, 3标识缩略图居中裁剪类型, 4标识缩略图左上角裁剪类型, 5标识缩略图右下角裁剪类型, 6标识缩略图固定尺寸缩放类型 */ function thumb($dir,$x,$y,$cut=3){ //提取图片日期文件夹名称 $ext =explode('/',$dir); //存储文件夹 $folder = 'public/uploads/'.$ext[3].'/thumb/'.$x.'_'.$y.'/'; //缩略图地址 $thmub = 'public/uploads/'.$ext[3].'/thumb/'.$x.'_'.$y.'/'.$ext[4]; //验证dir参数文件类型 $temp = explode('.',$dir); $extend = end($temp); $allowexts=array('jpg','png','gif','jpeg','JPG'); if(!in_array($extend,$allowexts)){ die(); } //判断力图片存在则输出 if(file_exists($thmub)){ return $thmub; } //必须是数字 if (!is_numeric($x) || !is_numeric($y)) { exit('图尺寸参数错误'); } //判断是否存在文件夹,没有则创建 if (stristr(PHP_OS,"WIN")) { $folder = iconv("UTF-8", "GBK", $folder); } if (!file_exists($folder)){mkdir ($folder,0777,true);} //生成缩略图 $image =substr($dir, 1); // 原图 $image = \think\Image::open($image); $image->thumb($x,$y,$cut)->save($thmub); return $thmub; } 调用,生成宽400 高320缩略图 <img src="{:thumb($imgSrc,440,320)}">
2 控制器
<?php // +---------------------------------------------------------------------- // | 生成指定尺寸的图片,用于部份展示位置对图片的优化,若指量使用请使用模型生成缩略图 2420355482@qq.com // | 使用方法例:生成宽300高200的尺寸图片 // | <img src="/api/thumb/index.html?dir=/public/uploads/20210805/610b9dfbb6394.jpg&x=300&y=200"> // +---------------------------------------------------------------------- namespace app\api\controller; use think\Controller; use think\Image; class Thumb extends Controller { public function index() { $x = input('get.x'); $y = input('get.y'); $dir = input('get.dir'); //提取图片日期文件夹名称 $ext =explode('/',$dir); //存储文件夹 $folder = 'public/uploads/'.$ext[3].'/thumb/'.$x.'_'.$y.'/'; //缩略图地址 $thmub = 'public/uploads/'.$ext[3].'/thumb/'.$x.'_'.$y.'/'.$ext[4]; //验证dir参数文件类型 $temp = explode('.',$dir); $extend = end($temp); $allowexts=array('jpg','png','gif','jpeg','JPG'); if(!in_array($extend,$allowexts)){ die(); } //判断力图片存在则输出 if(file_exists($thmub)){ header("Content-type: image/jpeg"); readfile($thmub); die(); } //必须是数字 if (!is_numeric($x) || !is_numeric($y)) { exit('图尺寸参数错误'); } //判断是否存在文件夹,没有则创建 if (stristr(PHP_OS,"WIN")) { $folder = iconv("UTF-8", "GBK", $folder); } if (!file_exists($folder)){mkdir ($folder,0777,true);} //生成缩略图 $image =substr($dir, 1); // 原图 $image = Image::open($image); $image->thumb($x,$y,2)->save($thmub); //输出缩略图 header("Content-type: image/jpeg"); readfile($thmub); die(); } }