歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> 使用Nginx自動裁剪圖片

使用Nginx自動裁剪圖片

日期:2017/3/1 16:18:08   编辑:關於Linux
使用Nginx自動裁剪圖片 使用Nginx進行圖片自動裁剪合符規范的圖片方法: 方法1:nginx自帶模塊 HttpImageFilterModule:http://wiki.nginx.org/HttpImageFilterModule 在編譯要帶上參數 --with-http_image_filter_module 配置nginx: #vi nginx.conf location ~* ^/img/pro/(.*)_RsT_(\d*)x(\d*)\.jpg$ { root /data/store/newvideo/video/ZhongXun/Web_images; rewrite /img/pro/(.*)_RsT_(\d*)x(\d*)\.jpg /$1 break; image_filter resize $2 $3; } 在使用方法1過程中,不知是我人品問題還是怎麼回事,只要是要裁剪的圖片超過1M,無論image_filter_buffer參數調成多大,總是報415 錯誤,網上也找不到什麼解決辦法,後來只能用方法2解決。 方法2:內嵌perl腳本實現 NginxEmbeddedPerlImageResize:http://wiki.nginx.org/NginxEmbeddedPerlImageResize 安裝ImageMagick # yum install ImageMagick ImageMagick-perl 在編譯nginx要帶上參數 --with-http_perl_module 配置nginx: http{ perl_modules perl/lib; perl_require resize.pm; server { ............. location ~* ^/img/pro/(.*)_RsT_(\d*)x(\d*)\.jpg$ { root /data/store/images; rewrite /img/pro/(.*)_RsT_(\d*)x(\d*)\.jpg /$1 break; image_filter resize $2 $3; error_page 415 = /$1_RsT_.$2x$3.jpg; } location /pic { root /data/store/images/; if (!-f $request_filename) { rewrite ^(.*)(.jpg|.JPG|.gif|.GIF|.png|.PNG)$ /resize$1$2 last; } } location /resize { perl resize::handler; } } } resize.pm的內容如下: package resize; use nginx; use Image::Magick; our $base_dir="/data/store/images"; #注意,如果nginx是使用其它用戶啟動的,啟動用戶一定要用這個目錄的寫權限 our $image; sub handler { my $r = shift; return DECLINED unless $r->uri =~ m/\.jpg_RsT_\.\d{1,}?x\d{1,}?\./; my $uri=$r->uri; $uri=~ s!^/resize!!; my $dest_file="$base_dir/$uri"; my @path_tokens=split("/", $uri); my $filename=pop @path_tokens; my @filename_tokens=split('\.', $filename); # We know the last part is the extension; # We know the one before that is the dimensions # We know that the one before that is the resize_to string my $ext=pop @filename_tokens; my $dimensions=pop @filename_tokens; pop @filename_tokens; $filename=join('.', @filename_tokens, $ext); my $real_file_path=join("/", $base_dir, @path_tokens, $filename); return DECLINED unless -f $real_file_path; my ($width,$height)=split("x", $dimensions); if ($height<1) { $dimensions=$width; } $image= new Image::Magick; $image->Read($real_file_path); $image->Scale($dimensions); $image->Write($dest_file); $r->sendfile($dest_file); return OK; }
Copyright © Linux教程網 All Rights Reserved