用Nginx的HttpImageFilterModule模块搭建缩略图服务器

HttpImageFilterModule用来处理转换图片(JPEG、GIF和PNG),是nginx自带的模块,默认不会开启,需要在编译安装的时候加上参数–with-http_image_filter_module

在使用这个模块之前,还需要libgd的支持

安装完成之后的配置如下:

server{
   listen 80;
   server_name img0.sinapp.cn img1.sinapp.cn;

location ~ /img/(\\d+)/(.*)_(\\d+){
    rewrite "/img/(\\d+)/(.*)_(\\d+)" /img/$1/$2 break ;
    image_filter   resize  $3 -;
    image\_filter\_buffer 20M;
    image\_filter\_jpeg_quality       51;
    include conf/proxy.conf;
}

location / {
    root "/data/img";
    default_type image/jpeg;
}
expires max;

}

之后,便可以用http://img0.sinapp.cn/img/2014/02/28a0b773b820de7dacf01559f2bfe5fa.jpg_200的方式访问到原图为http://img0.sinapp.cn/img/2014/02/28a0b773b820de7dacf01559f2bfe5fa.jpg的缩略图。

缩略图后面的_200代表缩略图宽度,压缩为等比压缩,当然也可以指定宽高压缩,一般不用这种方式。

HttpImageFilterModule模块主要有以下参数可用:

image_filter:指定模块处理图片的类型,比如裁剪、resize或者返回图片信息,有以下几个参数:

image_filter off #关闭,默认值
image_filter test #测试是否是图片(JPEG、GIF、PNG),否的话返回415错误
image_filter size #获取图片信息(JSON),比如{ “img” : { “width”: 100, “height”: 100, “type”: “gif” } }
image_filter rotate 90 | 180 | 270 #旋转图片
image_filter resize width height #改变图片的大小
image_filter crop width height #裁剪图片到指定大小

其它的参数如下:

image_filter_buffer 1m #指定可读取图片的大小,默认是1M
image_filter_jpeg_quality 75 #设置JPEG图片压缩的质量,默认是75,建议最大不要超过90
image_filter_sharpen 0 #设置锐化度,默认是0
image_filter_transparency on #这是是否透明,默认是on,用在PNG或GIF图片上