先前条件:第一步安装compose,已安装忽略。
先上截图看效果
一、在fastadmin的根目录里面输入命令安装think-image
composer require topthink/think-image
二、找到公共上传类,application/common/library/Upload.php,在最下面新添加一个压缩方法文章来源:https://www.toymoban.com/news/detail-801215.html
/**
* 图片压缩方法
*/
public function compressImage(&$params, $ratio = 10)
{
//图片大于300K才进行压缩,先判断是横图,还是坚图,设置图片宽最大820,高最大560,做出相对应的比例压缩
if ($params['filesize'] > 300000) {
//横图=宽比高大
if ($params['imagewidth'] >= $params['imageheight']) {
if ($params['imagewidth'] >= 820) {
$width = 820;
$height = round($params['imageheight'] / ($params['imagewidth'] / 820));
} else {
$width = $params['imagewidth'];
$height = $params['imageheight'];
}
} else { //坚图=高比宽大
if ($params['imageheight'] >= 560) {
$height = 560;
$width = round($params['imagewidth'] / ($params['imageheight'] / 560));
} else {
$width = $params['imagewidth'];
$height = $params['imageheight'];
}
}
$pathname = $params['url'];
$file = $this->file;
$image = \think\Image::open($file);
$image->thumb($width, $height)->save('.' . $pathname);
$image_root_path = ROOT_PATH . '/public' . $pathname;
$params['imagewidth'] = $width;
$params['imageheight'] = $height;
$params['filesize'] = filesize($image_root_path);
}
}
三、在application/common/library/Upload.php文件中,找到里面的 upload() 方法,在文件上传完成,将要添加到attachment表的图片数据时进行等比压缩处理
文章来源地址https://www.toymoban.com/news/detail-801215.html
// 开启压缩
if (in_array($this->fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($this->fileInfo['suffix'], ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
$this->compressImage($params);
}
到了这里,关于FastAdmin上传图片服务端压缩图片,实测13.45M压缩为29.91K的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!