-
下载依赖:composer require topthink/think-image
-
找到公共上传类application/common/library/Upload.php在最下面添加如下方法:
/**
* 等比压缩上传的图片,覆盖原图
* @Author: ELK
* @Date: 2022-1-10 16:10:28
* @param array $params 上传图片信息
* @param int $ratio 压缩比例
*/
public function thumb_image(&$params,$ratio = 10)
{
if($params['imagewidth'] > $ratio){
$width = $params['imagewidth'] / $ratio;
$height = $params['imageheight'] / $ratio;
$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);
}
}
/**
* 等比压缩上传的图片,保留原图,单独创建压缩图片
* @Author: ELK
* @Date: 2022-1-10 16:10:28
* @param array $params 上传图片信息
* @param int $ratio 期望压缩比例
*/
public function add_thumb_image(&$params,$ratio = 10)
{
if($params['imagewidth'] > $ratio){
$width = $params['imagewidth'] / $ratio;
$height = $params['imageheight'] / $ratio;
// 修改存储图片路径
$params['url'] = $pathname = str_replace('.','_thumb.',$params['url']);
$params['filename'] = str_replace('.','_thumb.',$params['filename']);
$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);
}
}
-
找到里面的 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->thumb_image($params);
}
-
保留原图单独创建压缩图片如下:
//等比压缩上传的图片,保留原图,单独创建压缩图片
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->add_thumb_image($params);
$attachment = new Attachment();
$attachment->data(array_filter($params));
$attachment->save();
}
5.测试:
-上传前图片大小:
-上传后图片大小: