http_image_filter_module用来裁剪图片的,是nginx自带模块,默认不会开启
开启该模块需要在编译时要带上参数 --with-http_image_filter_module
这里比如在tomcat服务器下放个 test 目录存放图片,则可以 http://ip:8080/test/234241.jpg 这样访问图片,安装裁剪模块后可以 http://ip:8080/test/234241_100x100_80.jpg 自动裁剪原图。
image_filter_module 没有真正生成裁剪/缩放后的图片,而是通过 Nginx 直接输出的,这样每次请求或缓存过期后都需要重新裁剪/缩放,会增加 Nginx 负担
需要下载的软件及模块:nginx-1.10.1.tar.gz,LuaJIT-2.0.3.tar.gz,pcre-8.35.tar.gz
pcre为了重写rewrite, zlib为了gzip压缩
yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel gd-devel
tar zxvf LuaJIT-2.0.3.tar.gz
sudo make && make install
配置变量
vi /etc/profile
export LUAJIT_LIB=/usr/local/lib
export LUAJIT_INC=/usr/local/include/luajit-2.0
执行下面命令
echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf
ldconfig
将pcre-8.35.tar.gz放到 /usr/local
下解压
tar zxvf pcre-8.35.tar.gz
tar zxvf nginx-1.10.1.tar.gz
cd nginx-1.10.1
./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_image_filter_module
--with-pcre=/usr/local/pcre-8.35
make
make install
make clean
在 /usr/local/nginx/servers
新建文件 image.test.com
server
{
listen 80;
server_name image.test.com;
index index.html index.htm index.php;
location / {
proxy_pass http://ip:8080/test/;
}
//裁剪图片尺寸 filename_100x100.jpg
location ~* .*_(\d+)x(\d+)\.(JPG|jpg|gif|png|PNG)$ {
set $img_width $1;
set $img_height $2;
rewrite ^(.*)_\d+x\d+.(JPG|jpg|gif|png|PNG)$ /test$1.$2 break;
image_filter resize $img_width $img_height;
image_filter_buffer 10M;
proxy_pass http://ip:8080;
}
//裁剪图片尺寸并压缩 filename_100x100_80.jpg
location ~* .*_(\d+)x(\d+)_(\d+)\.(JPG|jpg|gif|png|PNG)$ {
set $img_width $1;
set $img_height $2;
set $img_quality $3;
rewrite ^(.*)_\d+x\d+_\d+.(JPG|jpg|gif|png|PNG)$ /test$1.$2 break;
image_filter resize $img_width $img_height;
image_filter_buffer 10M;
image_filter_jpeg_quality $img_quality;
proxy_pass http://ip:8080;
}
}
image_filter_jpeg_quality
:设置jpeg图片的压缩质量比例(官方最高建议设置到95,但平时75就可以了);
image_filter_buffer
:限制图片最大读取大小,默认为1M;
image_filter_transparency
:用来禁用gif和palette-based的png图片的透明度,以此来提高图片质量。
[参考资料]