`

灵活自定义缩略图片尺寸大小方案分享(nginx,lua_nginx,GraphicsMagick)

 
阅读更多
melin 写道
    在开发电子商务网站时,同一个图片需要不同尺寸的缩略图片,一般有两种策略生成缩略图,一种在上传图片时,生成需要的缩略图,另一种是请求指定尺寸的图片时生存缩略图片,第一种方式有一定限制,就是需要提前知道所有尺寸的图片,而第二种方式更加灵活,这里采用第二种方案(也是查看taobao网站图片名称,猜想出来的方案,并加以验证,后来证实淘宝也是采用这个方案,只是淘宝使用ImageMagick)。
    这里主要借助lua_nginx module调用GraphicsMagick命令生存生存缩略图片,缩略图片的尺寸包含在请求图片名称中,例如:xxxxx.jpg.80x80.jpg返回的就是xxx.jpg的80x80尺寸的图片大小。nginx配置如下:
   
    上传图片名称使用32位随机字符替换掉,图片存放目录为图片名称前六个字母,每两个一组,构造三层目录结构存放,这样可以均匀存放图片在不同目录。避免目录存放文件数量限制。
    为了避免随意生成不同尺寸的缩略图,这里做了限制,在image_sizes中定义了需要的缩略图尺寸。
        location /testImg/ {
            rewrite_by_lua '
                local image_root = "/home/tomcat/eisp-files";
                function file_notexists(name)
                   local f=io.open(name,"r")
                   if f~=nil then io.close(f) return false else return true end
                end
                
								local uri = ngx.re.sub(ngx.var.uri, "/testImg/([0-9a-zA-Z]+)/([0-9a-zA-Z]{2})([0-9a-zA-Z]{2})([0-9a-zA-Z]{2})([0-9a-zA-Z]+).([0-9a-zA-Z]+)", "/images/$1/$2/$3/$4/$2$3$4$5.$6", "o");
                local index = string.find(uri, "([0-9]+)x([0-9]+)");
                local originalUri = string.sub(uri, 0, index-2);
                local area = string.sub(uri, index);
                index = string.find(area, "([.])");
                area = string.sub(area, 0, index-1);

                if file_notexists(image_root .. uri) then
                   local image_sizes = {"80x80", "800x600", "40x40"};
                   function table.contains(table, element)
                      for _, value in pairs(table) do
                         if value == element then
                            return true
                         end
                      end
                      return false
                   end

                   if table.contains(image_sizes, area) then
                       local command = "gm convert " .. image_root ..  originalUri  .. " -thumbnail " .. area .. " -background gray -gravity center -extent " .. area .. " " .. image_root .. uri;
                       os.execute(command);
                       ngx.req.set_uri(uri, true);
                   else
                       ngx.exit(404);
                   end;
                else
                   ngx.req.set_uri(uri, true);
                end;
            ';
        }

        location /images/ {
            alias /home/tomcat/eisp-files/images/;
            expires 7d;
        }


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics