网站上不同的页面需要不同尺寸的图片,或用户上传的图片尺寸不符合页面显示的规范,因此需要对图片尺寸进行加工。Nginx提供了一个图片处理模 块:http_image_filter_module,可以方便的对图片进行缩放、旋转等操作,可以实时对图片进行处理,支持nginx-0.7.54 以后的版本。
模块安装
1.安装gd-devel库
http_image_filter_module依赖gd-devel库,因此安装http_image_filter_module模块前需要首先安装gd-devel库。
Redhat、Centos运行如下命令安装:
# yum install -y gd-devel
Debian、Ubuntu运行如下命令安装:
# apt-get install libgd2-xpm libgd2-xpm-dev
2.安装http_image_filter_module模块
安装完gd-devel库后就可以重新编译安装nginx了,编译前需要./configurer指定编译http_image_filter_module模块:
# ./configure --prefix=/usr/local/nginx --with-http_image_filter_module # make && make install
注:nginx安装路径不同,对应的--prefix配置路径也不同。可执行:nginx -V命令查看安装参数
配置使用
安装完http_image_filter_module模块后,就可以在相应变站点的配置文件中增加如下配置,以启用图片压缩:
root /home/www/zszsgc/public; #站点根目录 location ~ "^(/upload/.*\.(jpg|png|jpeg))!(\d+)-(\d+)$" { set $w $3; set $h $4; rewrite ^(/upload/.*\.(jpg|png|jpeg))!(\d+)-(\d+)$ $1 break; image_filter resize $w $h; #按宽高对图片进行压缩 image_filter_buffer 2M; #设置图片缓冲区的最大大小,大小超过设定值,服务器将返回错误415 if (!-f $request_filename) { proxy_pass http://127.0.0.1:3000; } try_files $1 404; }
配置完成后,执行以下命令使配置生效:
# nginx -t -->检测配置是否正确 nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful # nginx -s reload -->使配置生效
以上规则将匹配/upload文件夹及其子文件夹下的.jpg.png.jpeg格式文件,如果文件名后有:!宽-高,格式的参数将按宽高进行压缩。
例如,有尺寸为980*735的源图片,图片网址为:
http://www.zszsgc.com/upload/2015/4/13/14288871450439949.jpg
现压缩为尺寸为320*250的缩略图,图片网址为:
http://www.zszsgc.com/upload/2015/4/13/14288871450439949.jpg!320-250
效果对比如下:
转自:
http://itbilu.com/other/relate/2015/04/14/NJFxwiVW.html
你打算打赏多少钱呢?
(微信扫一扫)