nginx+lua+GraphicsMagick做实时图片裁剪

来源:互联网 发布:cf卡修复软件 编辑:程序博客网 时间:2024/05/10 10:53
环境:我本地的虚拟机centos6.2
nginx和lua安装这里略过

1. 公司某图片服务器要做图片实时裁剪,nginx自带的有ngx_http_image_filter_module,但这个模块使用的GD,GD性能效率及处理后的图片质量都不如GraphicsMagick,并且裁剪后也不会保存,这样每次请求过来都要重新裁剪,所以访问很慢。于是就就想到裁剪后放一个目录,并做好过期或定期删除,访问时就去判断,有裁剪后的就取,没有的再做裁剪。

2.GraphicsMagick下载安装:
wget http://sourceforge.net/projects/graphicsmagick/files/graphicsmagick-history/1.3/GraphicsMagick-1.3.12.tar.gz
tar -zxvf GraphicsMagick-1.3.12.tar.gz
cd GraphicsMagick-1.3.12
./configure --prefix=/usr/local/GraphicsMagick --enable-shared
make && make install

验证下是否安装ok
输入 /usr/local/GraphicsMagick/bin/gm version

如果有出来相关信息,说明ok 


方案1.
location ~ '/csp/(.*)_([0-9]+)x([0-9]+).jpg$' {
    root /usr/local/nginx/html;
    set $image_root '/usr/local/nginx/html';
    set $fileName $1;
    set $width  $2;
    set $height $3;
    set $suffix ".jpg";
    set $th_suffix1 "_";
    set $th_suffix2 "csp";
    set $th_suffix3 "x";
    set $th_suffix4 "images/csp";
    set $origin_path  $image_root/$th_suffix2/$fileName;
    set $thumbnail_file_path $image_root/$th_suffix4/$fileName$th_suffix1$width$th_suffix3$height$suffix;
    if ( -f $thumbnail_file_path ) {
        root /usr/local/nginx/html/images;
    }
    if (!-f $thumbnail_file_path) {
        rewrite_by_lua '
            local gm_path = "/usr/local/GraphicsMagick/bin/gm convert "
            local command = gm_path .. ngx.var.origin_path.." -thumbnail "..ngx.var.width.."x" .. ngx.var.height .. "!" .. " " .. ngx.var.thumbnail_file_path;
            os.execute(command)
            local uri_path = "/" .. "csp"  .. "/" .. ngx.var.fileName .. ngx.var.th_suffix1 .. ngx.var.width .. ngx.var.th_suffix3 .. ngx.var.height .. ngx.var.suffix
            ngx.req.set_uri(uri_path)
            ngx.exec(uri_path)
         ';
        }
    } 

思路:匹配进来location后获取需要的值,第一个if判断访问的裁剪图片存在的情况,是,则给图片路径,这里郁闷的就是nginx这个配置里不能else,不然这直接来个else多干净,这种机制决定,没办法,又得来个if是判断这个图片文件不存在的情况,然后进入rewrite阶段进行裁剪,找到原图地址并进行裁剪后保存到指定的目录,

       方案二就不展示了,毕竟是公司生产环境正式用的,方法都差不多的。



0 0
原创粉丝点击