nginx图片过滤处理模块http_image_filter_module安装配置
一、http_image_filter_module说明
http_image_filter_module是nginx提供的集成图片处理模块,支持nginx-0.7.54以后的版本,在网站访问量不是很高磁盘有限不想生成多余的图片文件的前提下可,就可以用它实时缩放图片,旋转图片,验证图片有效性以及获取图片宽高以及图片类型信息,由于是即时计算的结果,所以网站访问量大的话,不建议使用。
安装还是很简单的,默认HttpImageFilterModule模块是不会编译进nginx的,所以要在configure时候指定
./configure arguments: --prefix=/usr/local/nginx --with-http_image_filter_module
PS: HttpImageFilterModule模块需要依赖gd-devel的支持,可以使用yum或apt-get方便地安装,如果未安装回报“/configure: error: the HTTP image filter module requires the GD library.”错误
yum install gd-devel
ubuntu系统:
apt-get install libgd2-xpm libgd2-xpm-dev
make&&make install后就可以进行配置了,做最简单的配置,先让模块可以跑起来^^
location ~ /simg/.*\.jpg$ {
#proxy_pass http://10.11.11.11;
#rewrite "/simg/(.*\.jpg)$" /img/$1 break ;
image_filter resize 100 100;
error_page 415 = /empty;
}
最后开启nginx,这样访问/simg/目录下的图片,都会按照高度最高100并且宽度最高100按照原图比例进行截取出来,并输出给浏览器。当然也可以开启重写去读取本机另一个目录下源文件;如果不在一台机器上就可以开启proxy_pass,并加上重写即可。
http_image_filter_module支持5种指令:
image_filter:测试图片文件合法性(image_filter test);3个角度旋转图片(image_filter rotate 90 | 180 | 270);以json格式输出图片宽度、高度、类型(image_filter size);最小边缩小图片保持图片完整性(resize width height);以及最大边缩放图片后截取多余的部分(image_filter crop [width] [height]);
image_filter_jpeg_quality:设置jpeg图片的压缩质量比例(官方最高建议设置到95,但平时75就可以了);
image_filter_buffer:限制图片最大读取大小,默认为1M;
image_filter_transparency:用来禁用gif和palette-based的png图片的透明度,以此来提高图片质量。
image_filter_sharpen:这个指令在nginx-1.1.8和1.0.11版本后增加的,目前还不知道是干啥用
二、配置实例
场景:
假如图片请求为(例子): /img001/2015/02/27/sd/gf/df/asdgasdgasgdasldgjhk.jpg
缩略图请求规则为(例子):/img001/2015/02/27/sd/gf/df/asdgasdgasgdasldgjhk.jpg?w=100&h=100
则,nginx的配置如下:
location ~* "^/src/(.*)\.(jpg|png|gif)$" {
root /home/root4/imgServer/data;
try_files /$1.$2 /img/notfount.jpg;
}
location ~* "^/img(.*)\.(jpg|png|gif)" {
root /home/root4/imgServer/data;
set $img_width "0";
set $img_height "0";
set $img_path $uri;
set $resize_width "-";
set $resize_height "-";
if ($arg_h != "") {
set $img_height $arg_h;
set $resize_height $arg_h;
}
if ($arg_w != ""){
set $img_width $arg_w;
set $resize_width $arg_w;
}
set $img_empty $img_width$img_height;
if ($img_empty = "00") {
rewrite /(.*)\.(jpg) /src/$1.$2 last;
}
if ($img_height = "0"){
set $resize_height "-";
}
if ($img_width = "0"){
set $resize_width "-";
}
image_filter resize $resize_width $resize_height;
image_filter_buffer 10M;
try_files $img_path /img/notfount.jpg;
}