利用 nginx 扩展实现图片剪裁

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/technofiend/article/details/83790556

无缓存版本

第一步:安装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,你将看到的是缓存文件。

猜你喜欢

转载自blog.csdn.net/technofiend/article/details/83790556
今日推荐