首页 > 代码库 > Nginx缩略图 - nginx image filter

Nginx缩略图 - nginx image filter

1,目的

为了节省用户下载图片的流量,我们可以在适当的地方使用图片缩略图技术。

2,使用方式

原始图片url

http://xx.xx.xx.xx/xx/xx/abc.jpg

 

缩略图片url

http://xx.xx.xx.xx/xx/xx/abc.jpg!wxh[.jpg|.png]

最后面的.png|.jpg可选

如果希望width/height按比例缩放,设置为 -

 

1),限制图片返回的宽度最大为200

http://xx.xx.xx.xx/xx/xx/abc.jpg!200x-

 

2),限制图片返回的高度最大为200

http://xx.xx.xx.xx/xx/xx/abc.jpg!-x200

 

3),限制图片返回宽度不超过200,高度不超过300

http://xx.xx.xx.xx/xx/xx/abc.jpg!200x300

 

4),例子:

http://192.168.85.197/Mobile/jiefang/server/prod/upload/01.jpg                    805k

http://192.168.85.197/Mobile/jiefang/server/prod/upload/01.jpg!200x-           17k

 

http://192.168.85.197/Mobile/jiefang/server/prod/upload/02.png                    698k

http://192.168.85.197/Mobile/jiefang/server/prod/upload/02.png!200x200      79k

 

http://192.168.85.197/Mobile/jiefang/server/prod/upload/03.jpg                     300k

http://192.168.85.197/Mobile/jiefang/server/prod/upload/03.jpg!300x-            15k

3,原理

利用nginx image filter模块实时压缩图片

1),当访问的缩略图不存在,则根据原始图片实时生成对应尺寸的缩略图片,并把缩略图保存到磁盘。(图片缩放时会消耗部分CPU计算)

2),如果缩略图已经存在,则直接返回磁盘上的缩略图。

特点:支持缩略图写磁盘,不支持水印。

4,配置实现

#nginx-tomcat.conf
location ~ ^/Mobile/jiefang/* { root /home/wwwroot/ftp; set $width "-"; set $height "-"; if ( $uri ~ "/(.{1,}\..+)!([\d|-]+)x([\d|-]+).*" ) { set $width $2; set $height $3; set $image_path $1; } set $image_uri thumb_image/$image_path?width=$width&height=$height; if (!-f $request_filename) { #如果缩略图不存在,则实时生成。 proxy_pass http://127.0.0.1/$image_uri; break; } proxy_store on; #/home/wwwroot/ftp/$request_filename; #on表示压缩后的文件保存在与源图片相同目录下。 proxy_store_access user:rw group:rw all:r; #proxy_temp_path /tmp/images; proxy_set_header Host $host; proxy_set_header Content-Type image/jpeg; } location /thumb_image { alias /home/wwwroot/ftp; image_filter resize $arg_width $arg_height; image_filter_jpeg_quality 75; # 压缩质量 #image_filter_buffer 2m; # 如果原始图片大小起过1m,则会报415错误 if ( $request_filename ~ "/home/wwwroot/ftp/(.*)" ) { error_page 415 = http://$host/$1; # 如果出错,则使用原始图片 } allow 127.0.0.0/8; deny all; }

nginx编译参数:

--with-http_image_filter_module

 

5,参考资料

http://nginx.org/en/docs/http/ngx_http_image_filter_module.html
http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_store
https://github.com/3078825/ngx_image_thumb

Nginx缩略图 - nginx image filter