nginx中如何没有添加http_image_filter_module
的话重新启动的时候会提示语法错误,所以需要给nginx添加http_image_filter_module
,可以查看我的这篇文章作参考
http_image_filter
是一个过滤器,它能处理JPEG, GIF, PNG和WebP格式的图片。
image_filter
image_filter
只能用在location
里面, 语法
image_filter off;
image_filter test;
image_filter size;
image_filter rotate 90 | 180 | 270;
image_filter resize width height;
image_filter crop width height;
off
默认选项。不使用模块来处理图片,在location
我们添加image_filter
的任何配置,默认就不会使用模块来处理图片
test
nginx
添加完http_image_filter
模块之后我们可以用这个指令来测试模块是否正常工作。可以在一个测试的location
中添加该模块。
location /test {
image_filter test;
return 404;
}
如果响应是JPEG, GIF, PNG, or WebP格式的话会正常返回图片,否则会报一个415
错误。
我在上面的转发中直接return 404
,这时候请求客户端并不会看到404
响应,而是一个415 Unsupported Media Type
的错误。
如果在使用image_filter的过程中出现了415错误,那就要考虑是否是响应内容有问题,当然还有一种情况会415,那就是图片过大的情况,默认只能处理1M以内的图片,不过我们可以使用image_filter_buffer
来解决
size
location /test {
image_filter size;
...
}
这时候会把响应替换为图片的尺寸信息,也包含图片类型。
{ "img" : { "width": 36, "height": 36, "type": "png" } }
如果请求图片出错,会得到{}
rotate 90|180|270
顾名思义旋转图片,但是只能是90|180|270
这三个值,逆时针旋转。
location /test {
image_filter 90;
...
}
有尝试使用其他的数值,但是nginx -t
校验语法不通过。
也支持使用变量,但是如果变量值不是上面指定的三个值的话会报415
错误。
# 会报415错误
location /test {
set $deg 45;
image_filter rotate $deg;
...
}
resize width height
改变(验证发现似乎只能压缩不能放大)图片的宽高, 可以用来构建动态缩略图服务
-
同时可以同时指定宽高 同时指定宽高的时候会按照宽度等比例压缩,不清楚是我漏了配置还是怎么回事
location /test { image_filter resize 200 100; ... }
-
可以只制定其中一个值,另外一个用
-
代替,代表自适应location /test { image_filter resize 200 -; # image_filter resize - 200; ... }
-
可以搭配
rotate
使用location /test { image_filter resize 200 -; image_filter rotate 90; ... }
-
可以使用变量
使用变量就比较灵活了 这里写两个仅供参考
通过
get
参数设置location /test { image_filter resize $arg_width -; ... }
此时访问图片的时候带上参数
x.png?width=100
会把图片缩放到100高度自适应。利用正则匹配
location ~ ^/test/(.*)\.(jpg|jpeg|gif|png)(!(\d+)?)?$ { set $wg $4; set $width -; if ($wg != "") { set $width $wg; } image_filter resize $width -; alias /Pictures/$1.$2; }
请求地址:
x.png!100
crop width height
按指定宽高裁剪图片,使用方法和resize基本一致,就不过多介绍了。
image_filter_buffer
设置读取图片时候最大的buffer大小,如果超出会报415
错误
location /text {
image_filter_buffer 2M;
}
默认buffer的大小为1M,image_filter_buffer
可以在http,server,location
内部使用
其他因为没有用到就没过多接触,想了解更多的话可以查看官方文档