在TP6中,可以放到common.php中,重复利用。代码中设置了临时文件、上传目录和压缩倍数3个参数,也可以根据实际增加参数。使用php gd库,需要确认gd库是否加载。代码如下:
php
function image_composer($file_tmp,$dir,$ratio)
{
// 获取当前时间的毫秒数(包含秒和毫秒)
$milliseconds = round(microtime(true) * 1000);
//设置保存目录
$uploadDir = $dir. '/'. $milliseconds .'.jpg';
// 获取图片信息
$imageInfo = getimagesize($file_tmp);
$source = imagecreatefromjpeg($file_tmp);
// 获取原始图片尺寸
list($width, $height) = $imageInfo;
// 设置新的图片尺寸(例如宽度为原来的一半)
$newWidth = $width / $ratio;
$newHeight = $height / $ratio;
// 创建新的图片资源
$newImage = imagecreatetruecolor($newWidth, $newHeight);
// 调整图片尺寸
imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($newImage, $uploadDir, 80);
// 释放内存
imagedestroy($newImage);
imagedestroy($source);
return $uploadDir;
}