Nginx安裝http_image_filter_module圖片裁剪模組

gary-liu發表於2016-09-30

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

yum安裝nginx依賴模組

pcre為了重寫rewrite, zlib為了gzip壓縮

yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel gd-devel

編譯安裝LuaJIT

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

編譯安裝 nginx

將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圖片的透明度,以此來提高圖片質量。

[參考資料]

丁丁的開發日記

相關文章