背景:手机拍照一般3M,上传后如果不压缩,浏览时图片打开慢,只能一张一张加载出,用户体验不好
库地址:https://github.com/Intervention/image
方法一:使用resize方法,更改图片宽度和高度
use Intervention\Image\Facades\Image;
$image = Image::make($image_path);
//宽、高较大者在600以内的图片不压缩
$size = 600;
if ($width >= $height) {
if ($width>$size) {
//宽度变为50%,高度等比例缩小
$image->resize(ceil($width/2), null, function ($constraint) {
$constraint->aspectRatio();
});
}
} else {
if ($height>$size) {
//高度变为50%,宽度等比例缩小
$image->resize(null, ceil($height/2), function ($constraint) {
$constraint->aspectRatio();
});
}
}
//更改原文件
$image->save($image_path);
方法二:不更改原来的宽和高,只损失质量,来缩小图片
use Intervention\Image\Facades\Image;
$image = Image::make($image_path);
$image->save($image_path,60);//第二个参数是质量,详情见官方文档