分享

nignx实现图片截图与缓存( 一)

一,使用Nginx插件 image_filter

  1. 在nginx.conf配置如下
    # 我使用16进制数的方式给图片重命名
    location~*/(.*)\/([0-9a-f]+)_(\d+)x(\d+)\.(jpg|png|jpeg|gif)${
       # 如果存在文件就终止规则
       if(-f $request_filename){
           break;
       }
       
       # 设定一些参数
       set$filepath $1;
       set$filename"$2.$5";
       set$thumb    "$2_$3x$4.$5";
       set$width    $3;
       set$height   $4;
       
       # 如果原文件不存在可以直接返回404
       if(!-f $document_root/$filepath/$filename){
           return404;
       }
       # 重写URL
       rewrite/(.*)\/([0-9a-f]+)_([0-9x]+)\.(jpg|png|jpeg|gif)/$1/$2.$4break;
       # 执行图片缩放
       image_filter test;
       image_filter resize $width $height;
       image_filter_jpeg_quality75;
    }

    2.重启nginx ,然后就可以访问了 : http://localhost:8080/mglsoft/1_600x600.jpg

    3.在公司重新整理了一下

    location~*/(.*)\/([0-9a-f]+)\.(jpg|png|jpeg|gif)@(\d+)x(\d+)Q_([rc])${
               if(-f $request_filename){
                   break;
               }
               set$filepath $1;
               set$filename"$2.$3";
               set$thumb    "$2_$4x$5.$3";
               set$width    $4;
               set$height   $5;
               set$type    $6;
               if($type='r'){
                   set $type  'image-resize'; #旋转
               }
           
               if($type='c'){
                 set$type  'image-crop';#剪切
             }
           
               if(!-f $document_root/$filepath/$filename){
                   return404;
               }
               rewrite/(.*)\/([0-9a-fx_]+)\.(.*)/imgcache/$2.$4;
               if(!-f $request_filename){
                   proxy_pass $scheme://127.0.0.1:$server_port/$type/$filepath/$filename?width=$width&height=$height;
                   break;
               }
               proxy_store          $document_root/imgcache/$thumb;
               proxy_store_access   user:rw  group:rw  all:r;
               proxy_set_header    Host$host;
               expires  10d;# 设置图片过期时间10天
           }
           location/image-resize{
               rewrite/(image-resize)/(.*)/$2break;
               image_filter resize $arg_width $arg_height;
               image_filter_jpeg_quality75;
               #allow 127.0.0.0/8;
               #deny all;
           }
           location/image-crop{
               rewrite/(image-crop)/(.*)/$2break;
               image_filter crop $arg_width $arg_height;
               image_filter_jpeg_quality75;
               #allow 127.0.0.0/8;
               #deny all;
           }
       }

    通过以下路径访问: http://域名.com/test/a.jpg@240x210Q_r

留言