nginx实时生成缩略图到硬盘上

aries 发表于 2018-04-28 1799 次浏览

现在随着各终端的出现(手机,ipad等平板),以及各种终端的手机分辨率和尺寸都不同,现在手机用户流量都是宝,网上出现了各种各样的生成缩略图功能的架构,有使用php实时生成缩略图的,也有用nginx + lua实现的,以前我们也写过《使用nginx生成缩略图》,但是用户每次访问都需要生成一次,会给cpu和硬盘带来比较大的压力,今天带来了另外一种方式,这次使用nginx将原图生成缩略图到硬盘上.看我的配置。

首先建好cache目录

# mkdir $document_root/imgcache/
# chmod -R 777 $document_root/imgcache/

修改nginx配置

set $rule_root $document_root;

#匹配如http://blog.iw3c.com/upload/abc/efg/abcefg123.jpg@900x700Q_r这种地址

location ~* /upload/(.*)/(.*)/([0-9a-z]+).(jpg|png|jpeg|gif)@(d+)x(d+)Q_([rc]){
    if (-f $request_filename) {
        break;
    }
    set $filepath "upload/$1/$2";
    set $filename "$3.$4";
    set $thumb    "$3_$5x$6.$4";
    set $width    $5;
    set $height   $6;
    set $type    $7;
    if ( $type = 'r' ){
        set  $type   'image-resize';   #旋转
    }

    if ( $type = 'c' ){
      set $type  'image-crop'; #剪切
   }
    if (!-f $document_root/$filepath/$filename) {
        return 404;
    }
    rewrite /upload/(.*)/(.*)/([0-9a-z]+).(.*) /imgcache/$1/$2/$thumb;
    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/$1/$2/$thumb;
    #注意proxy_temp一定要有权限读写
    proxy_store_access   user:rw  group:rw  all:r;
    proxy_set_header     Host $host;
    expires  10d; # 设置图片过期时间10天
}
location ^~ /image-resize {
    alias $rule_root/;
    image_filter resize $arg_width $arg_height;
    image_filter_jpeg_quality 75;
    image_filter_buffer 20m;
    #allow 127.0.0.0/8;
    #deny all;
}
location ^~ /image-crop {
    alias $rule_root/;
    image_filter crop $arg_width $arg_height;
    image_filter_jpeg_quality 75;
    image_filter_buffer 20m;
    #allow 127.0.0.0/8;
    #deny all;
}

生成缩略图流程如下:

1、原图在blog.iw3c.com/upload/abc/efg/abcefg123.jpg。我需要一份100×100的缩略图。

2、请求blog.iw3c.com/upload/abc/efg/abcefg123.jpg@100x100Q_r.

3、这个请求进入了第一个location,接着判断imgcache这个目录下是否存在这张图片,如果存在直接通过重写放回给用户,

4、不存在那么反向代理到http://127.0.0.1/image-resize/upload/abc/efg/abcefg123.jpg?width=100&height=100,如果执行了proxy_pass,那么下面的proxy_store生效,缓存图片;

5、location /image-resize根据传入的width和height执行缩略功能,并且设置图像质量为75

6、接着生成文件到imgcache/abc/efg/abcefg123.jpg_100x100.jpg

7、并且返回图片给用户

8、nginx生成缩略图到硬盘上的功能到这里就结束了

0条评论

如需评论,请填写表单。
换一个

记住我的信息