topthink/think-image
https://www.kancloud.cn/manual/thinkphp5/177530
根据拼接图片路径获取图片,这样可以减少图片服务器的带宽占用,常见有阿里云,七牛云的图像处理
例如 原图大小是720*720
http://192.168.0.24:63343/storage/avatar/20210531/8ac683182527aa520f0a8de8a9ff6a82.jpg
这样拿到的是360*360的
http://192.168.0.24:63343/storage/avatar/20210531/8ac683182527aa520f0a8de8a9ff6a82_360_360.jpg
需要修改
.htaccess文件
这个配置文件很强大,包括诸如服务器缓存,图片防盗链(一个是版权,一个也是减少服务器带宽占用),网络请求压缩html等等
https://blog.youkuaiyun.com/kakuma_chen/article/details/71465251
原理如下
https://www.cnblogs.com/heyue0117/p/12109669.html
1、开启apache的rewrite功能。
https://jingyan.baidu.com/article/8275fc868c1a7946a03cf6ef.html
小皮打开
2、修改.htaccess
<IfModule mod_rewrite.c>
Options +FollowSymlinks -Multiviews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^storage/(.*)/(.*)/(.*)_(\d+)_(\d+).(png|jpg|jpeg|gif)$ /index/thumbnail/module/$1/date/$2/original/$3/width/$4/height/$5/ext/$6 [L,R]
</IfModule>
Index Conrtroller下的thumbnail方法
public function thumbnail()
{
//$savePath = Config::get('attachment_path');
$savePath = Filesystem::getDiskConfig('public','root').'/';
$defaultImage = $savePath . 'default.ipg';
$params = Request::instance()->param();
$module = $params['module'];//图片所属模块
$date = $params['date']; // 图片上传日期
$original = $params['original']; // 原始图片名称(不含后缀)
$width = $params['width']; // 目标图片宽度
$height = $params['height'];// 目标图片高度
$ext = $params['ext']; //图片后缀
$originName = sprintf('%s%s/%s/%s.%s', $savePath, $module, $date, $original, $ext);
$targetName = sprintf('%s%s/%s/%s_%s_%s.%s', $savePath, $module, $date, $original, $width, $height, $ext);
if (!file_exists($originName)) {
$originName = $defaultImage;
$targetName = sprintf('%sdefault_%s_%s.ipg', $savePath, $width, $height);
}
$image = Image::open($originName);
$thumb = $image->thumb($width, $height);
if (!file_exists($targetName)) {
$thumb->save($targetName);
}
$thumb->preview();
}
composer依赖了topthink/think-image之后
库的Image.php新增扩展方法
/**
* @param int $quality 图像质量
* @param bool $interlace 是否对JPEG类型图像设置隔行扫描
*/
public function preview($quality = 100, $interlace = true)
{
$type = $this->info['type'];
header('content-type:' . $this->info['mime']);
if ('jpeg' == $type || 'jpg' == $type) {
//JPEG图像设置隔行扫描
imageinterlace($this->im, $interlace);
imagejpeg($this->im, null, $quality);
} elseif ('gif' == $type && !empty($this->gif)) {
imagegif($this->im, null);
} elseif ('png' == $type) {
//设定保存完整的 alpha 通道信息
imagesavealpha($this->im, true);
//ImagePNG生成图像的质量范围从0到9的
imagepng($this->im, null, min((int)($quality / 10), 9));
} else {
$fun = 'image' . $type;
$fun($this->im, '');
}
exit;
}