---
title: "nginx系列(二十二)nginx的图片过滤处理模块http_image_filter_module"
author: "85977328"
date: "2015-11-22T14:13:38Z"
tags: []
categories: ["互联网"]
slug: "nginx-nginx-http-image-filter-module"
draft: false
lastmod: "2023-02-17T17:08:30Z"
id: 2258375
url: "https://phl.iteye.com/blog/2258375"
---

http_image_filter_module是nginx提供的集成图片处理模块，支持nginx-0.7.54以后的版本，在网站访问量不是很高磁盘有限不想生成多余的图片文件的前提下可，就可以用它实时缩放图片，旋转图片，验证图片有效性以及获取图片宽高以及图片类型信息，由于是即时计算的结果，所以网站访问量大的话，不建议使用。或者nginx前面再加一层缓存。

安装还是很简单的，默认HttpImageFilterModule模块是不会编译进nginx的，所以要在configure时候指定
./configure --prefix=/usr/local/nginx --with-http_image_filter_module

HttpImageFilterModule模块需要依赖gd-devel的支持，可以使用yum或apt-get方便地安装，如果未安装回报“/configure: error: the HTTP image filter module requires the GD library.”错误
centos办法
yum install gd-devel
ubuntu办法
apt-get install libgd2-xpm libgd2-xpm-dev
make && make install后就可以进行配置了，做最简单的配置，先让模块可以跑起来
location / {
    root   html;
    index  index.html index.htm;
}

location ~ /image/.*\.jpg$ {
    #proxy_pass     http://192.168.1.1;
    #rewrite "/image/(.*\.jpg)$" /img/$1 break;
    image_filter   resize  100 100;
    error_page     415   = /empty;
}
最后开启nginx，这样访问/image/目录下的图片，都会按照高度最高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  ）；

image_filter_jpeg_quality：设置jpeg图片的压缩质量比例（官方最高建议设置到95，但平时75就可以了）；

image_filter_buffer：限制图片最大读取大小，默认为1M；

image_filter_transparency：用来禁用gif和palette-based的png图片的透明度，以此来提高图片质量。

image_filter_sharpen：暂时未知。

其他用法
        location ~* /(\w+)\.(jpg)$ {
            set $h $arg_h; #获取参数h的值
            set $w $arg_w; #获取参数w的值
            #image filter crop $h $w;
            image_filter resize $h $w; #根据给定的长宽生成缩略图
        }

        location ~* /(\w+)_(\d+)×(\d+)\.(jpg)$ {
            if (-e $document_root/$1.$4) {
                rewrite /(\w+)_(\d+)×(\d+)\.(jpg)$ /$1.$4?h=$2&w=$3 last;
            }
            return 404;
        }


在nginx的html目录下，上传图片123.jpg
通过浏览器访问
http://192.168.56.2:8080/123_800×800.jpg