先前条件:第一步安装compose,已安装忽略。
先上截图看效果
一、在fastadmin的根目录里面输入命令安装think-image
composer require topthink/think-image
二、找到公共上传类,application/common/library/Upload.php,在最下面新添加一个压缩方法
/*** 图片压缩方法*/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表的图片数据时进行等比压缩处理
// 开启压缩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);}