Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 知乎專欄 | Search | Email

45.8. image_filter

image_filter 配置項:
image_filter off;    在所在location關閉模組處理。
image_filter test;  確保應答是JPEG,GIF或PNG格式的圖像。否則錯誤 415 (Unsupported Media Type) 將被返回。
image_filter size;  以JSON格式返回圖像信息。
image_filter rotate 90 | 180 | 270;  將圖像逆時針旋轉指定角度。 參數的值可以包含變數。 可以單獨使用,或與 resize 和 crop 變換同時使用.
image_filter resize width height;  按比例縮小圖像至指定大小。 如果想只指定其中一維,另一維可以指定為: “-”。 如果有錯誤發生,伺服器會返回 415 (Unsupported Media Type). 參數的值可以包含變數。 當與 rotate 參數同時使用時, 旋轉發生在縮放 之後。 
image_filter crop width height;  按比例以圖像的最短邊為準對圖像大小進行縮小,然後裁剪另一邊多出來的部分。 如果想只指定其中一維,另一維可以指定為: “-”。 如果有錯誤發生,伺服器會返回 415 (Unsupported Media Type). 參數的值可以包含變數。 當與 rotate 參數同時使用時, 旋轉發生在裁剪 之前。

image_filter_buffer 配置項:
image_filter_buffer size; 例如 image_filter_buffer 1M; 設置用來讀圖像的緩衝區的最大值。 若圖像超過這個大小,伺服器會返回 415 (Unsupported Media Type).
image_filter_jpeg_quality quality; 例如 image_filter_jpeg_quality 75;設置變換後的JPEG圖像的 質量 。 可配置值: 1 ~ 100 。 更小的值意味着更差的圖像質量以及更少需要傳輸的數據。 推薦的最大值是95. 參數的值可以包含變數。
image_filter_sharpen percent; image_filter_sharpen 0;  增加最終圖像的鋭度。 鋭度百分比可以超過100. 0為關閉鋭化。 參數的值可以包含變數。
image_filter_transparency on|off; image_filter_transparency on;定義當對PNG,或者GIF圖像進行顏色變換時是否需要保留透明度。 損失透明度有可能可以獲得更高的圖像質量。 PNG圖像中的alpha通道的透明度預設會一直被保留。
 		
		
比如所有的圖片並修改尺寸為 800x600

       location ~* \.(jpg|gif|png)$ {
               image_filter resize 800 600;
       }

匹配images目錄所有圖片並修改尺寸為1920x1080

       location ~* /images/.*\.(jpg|gif|png)$ {
               image_filter resize 1920 1080;
       }


再比如用url來指定

location ~* (.*\.(jpg|gif|png))!(.*)x(.*)$ {
    set $width      $3;
    set $height     $4;
	rewrite "(.*\.(jpg|gif|png))(.*)$" $1;
}

location ~* .*\.(jpg|gif|png)$ {
	image_filter resize $width $height;
}

location ~* /images/(.+)_(d+)x(d+).(jpg|gif|png)$ {            
    set $height $2;
    set $width $3;
    if ($height = "0") {
        rewrite /images/(.+)_(d+)x(d+).(jpg|gif|png)$ /images/$1.$4 last;
    }
    if ($width = "0") {
        rewrite /images/(.+)_(d+)x(d+).(jpg|gif|png)$ /images/$1.$4 last;
    }

    #根據給定的長寬生成縮略圖
    image_filter resize $height $width;
    
    #原圖最大2M,要裁剪的圖片超過2M返回415錯誤,根據你的需求調節參數image_filter_buffer 
    image_filter_buffer 2M;                          
    
    #error_page  415      		/images/404.jpg;
    try_files /images/$1.$4  	/images/404.jpg;	
}

location ~* /images {
    
}
        
location ~* ^/images/resize/([\d\-]+)_([\d\-]+)/(.+) {  
    alias /www/example.com/img.example.com/$3;
    image_filter test;
    image_filter resize $1 $2;
    image_filter_buffer 2M;
    image_filter_jpeg_quality 95;
    image_filter_sharpen 90;
    expires 60d;
}