Nginx image_filter动态缩略图
2020-08-23 22:51:09
751次阅读
1个评论
URL 样式:http://域名/tu-${mod}300x300.jpg
Ps:${mod}表示缩略图裁剪模式,即 resize 或 crop。
在站点的 Server 模块中新增如下 location 规则:
https://域名/static/20190113/qiniucdn1.png
https://域名/wp-content/uploads/2015/05/qiniucdn1-resize400x400.png
https://域名/wp-content/uploads/2015/05/qiniucdn1-crop400x400.png
Ps:${mod}表示缩略图裁剪模式,即 resize 或 crop。
在站点的 Server 模块中新增如下 location 规则:
#resize裁剪模式配置
location ~* /(.+)-resize(d+)x(d+).(jpg|gif|png)$ {
set $width $2;
set $height $3;
#带长宽的图片实际是不存在的,所以重写到真实图片上
rewrite /(.+)-resize(d+)x(d+).(jpg|gif|png)$ /$1.$4 break;
#生成缩略图
image_filter resize $width $height;
image_filter_buffer 2M;
image_filter_jpeg_quality 80;
image_filter_transparency on;
#插入一个头部,测试中证明缩略图来自Nginx,测试无误可随时删除
add_header Thumbnail "By Nginx";
#如果找不到图片,将返回如下预设图片(请放置正确的图片)
try_files /$1.$4 /wp-content/uploads/files/notfound.jpg;
}
#crop裁剪模式配置
location ~* /(.+)-crop(d+)x(d+).(jpg|gif|png)$ {
set $width $2;
set $height $3;
#带长宽的图片实际是不存在的,所以重写到真实图片上
rewrite /(.+)-crop(d+)x(d+).(jpg|gif|png)$ /$1.$4 break;
#生成缩略图
image_filter crop $width $height;
image_filter_buffer 2M;
image_filter_jpeg_quality 80;
image_filter_transparency on;
#插入一个头部,测试中证明缩略图来自Nginx,测试无误可随时删除
add_header Thumbnail "By Nginx";
#如果找不到图片,将返回如下预设图片(请放置正确的图片)
try_files /$1.$4 /wp-content/uploads/files/notfound.jpg;
}
访问博客图片查看效果了,举例地址样式如下:https://域名/static/20190113/qiniucdn1.png
https://域名/wp-content/uploads/2015/05/qiniucdn1-resize400x400.png
https://域名/wp-content/uploads/2015/05/qiniucdn1-crop400x400.png
URL 样式:http://域名/tu.jpg?w=300&h=300
在站点的 Server 模块中新增如下 location 规则:
location ~ .*.(gif|jpg|jpeg|png|bmp)$ {
set $width '';
set $height '';
#将参数赋值给宽和高
set $width $arg_width;
set $height $arg_height;
#当存在参数请求(即请求的是缩略图),插入头部标识方便测试
if ( $width != '' ) {
add_header Thumbnail "By Nginx";
}
#当未设置高度时,仅使用宽度来进行缩放,可以保证图片的正常比例(适用于文章)
if ( $height = '' ) {
set $height '-';
}
#当请求的是原图时(即不带参数),则设置宽高维度为”-”
if ( $width = '' ) {
set $width '-';
set $height '-';
}
#生成缩略图
image_filter resize $width $height;
image_filter_buffer 2M;
image_filter_jpeg_quality 80;
image_filter_transparency on;
}
查看效果
https://域名/static/20190113/qiniucdn1.png
https://域名/static/20190113/qiniucdn1.png?width=480
https://域名/static/20190113/qiniucdn1.png?width=480&height=480
00