利用 nginx 擴充套件實現圖片剪裁
阿新 • • 發佈:2018-11-23
無快取版本
第一步:安裝nginx模組
ngx_http_image_filter_module,用寶塔linux一鍵安裝,有自帶。
第二步:修改配置
location ~ (.+?)_(\d+)x(\d+)\.(gif|jpg|jpeg|png|bmp|swf)$ { set $file $1_$2x$3_100.$4; rewrite ^.*$ $file last; } location ~ (.+?)_(\d+)x(\d+)_(\d+)\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; access_log off; set $file $1.$5; set $h $2; set $w $3; set $q $4; if ($h = '0') { rewrite ^.*$ $file last; } if ($w = '0') { rewrite ^.*$ $file last; } image_filter_jpeg_quality $q; # 根據給定的長寬生成縮圖 image_filter resize $h $w; # 根據給定的長寬剪裁圖片 image_filter crop $h $w; # 原圖最大2M,要裁剪的圖片超過2M返回415錯誤,需要調節引數image_filter_buffer image_filter_buffer 2M; # error_page 415 /notfound.jpg; try_files $file /notfound.jpg; }
第三步:測試
原圖:http://xxx.com/abc.jpg
裁剪100x100:http://xxx.com/abc_100x100.jpg
裁剪200x200:http://xxx.com/abc_200x200.jpg
裁剪200x200兼調整質量50:http://xxx.com/abc_200x200_50.jpg
裁剪200x200兼調整質量80:http://xxx.com/abc_200x200_80.jpg
帶檔案快取
第一步:安裝nginx模組
ngx_http_image_filter_module,用寶塔linux一鍵安裝,有自帶。
第二步:修改配置
新增一個配置檔案,並且監聽多一個埠,該配置專門用於縮圖片
server { listen 88; root /www/wwwroot/mn.com/public/; location / { image_filter_jpeg_quality $arg_quality; image_filter resize $arg_height $arg_width; image_filter crop $arg_height $arg_width; image_filter_buffer 2M; allow 127.0.0.0/8; deny all; } }
location ~ (.+?)_(\d+)x(\d+)\.(gif|jpg|jpeg|png|bmp|swf)$ { set $file $1_$2x$3_100.$4; rewrite ^.*$ $file last; } location ~ (.+?)_(\d+)x(\d+)_(\d+)\.(gif|jpg|jpeg|png|bmp|swf)$ { root /tmp/nginx/resize; expires 30d; access_log off; set $file $1.$5; set $h $2; set $w $3; set $q $4; if ($h = '0') { rewrite ^.*$ $file last; } if ($w = '0') { rewrite ^.*$ $file last; } set $image_uri $file?width=$w&height=$h&quality=$q; if (!-f $request_filename) { proxy_pass http://127.0.0.1:88/$image_uri; break; } # 此處配置快取的地方,我配置的是 /tmp/nginx/resize ,由本location的root決定 proxy_store $request_filename; proxy_store_access user:rw group:rw all:r; proxy_temp_path /tmp/images; proxy_set_header Host $host; }
第三步:測試
原圖:http://xxx.com/abc.jpg
裁剪100x100:http://xxx.com/abc_100x100.jpg
裁剪200x200:http://xxx.com/abc_200x200.jpg
裁剪200x200兼調整質量50:http://xxx.com/abc_200x200_50.jpg
裁剪200x200兼調整質量80:http://xxx.com/abc_200x200_80.jpg
用畫圖工具編輯/tmp/nginx/resize/下面的abc_200x200_80.jpg影象加點花,再次請求http://xxx.com/abc_200x200_80.jpg,你將看到的是快取檔案。