tp5 动态生成缩略图
<?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');
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,Image::THUMB_CENTER)->save($thmub);
//输出缩略图
header("Content-type: image/jpeg");
readfile($thmub);
die();
}
}注意你的图片存储路径可能不一样