使用Nginx自动裁剪图片

manzhe 2013-06-20

使用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;
}
 

相关推荐

lwplvx / 0评论 2020-11-22
岁月如歌 / 0评论 2020-07-21