Record

机会是留给有准备的人

OpenResty+GraphicsMagick为图片添加水印与缩略图

之前公司项目一直是用java+GraphicsMagick生成缩略图,开发起来非常繁琐。效率也不高。
后面就使用了这个方法,效果还行

nginx代码

location ~ .*\.(jpg|jpeg|png)$ {
        root   /data/image;
        set $image_root /data/image;
        set $file "$image_root$uri";
        if (!-f $file)
        {
            content_by_lua_file lua/image.lua;
        }
        proxy_next_upstream http_502 http_504 error timeout invalid_header;
        proxy_cache_valid  200 304 12h;
        proxy_cache_key $uri$is_args$args;
        index  index.html index.htm;
        expires 7d;
    }

lua代码

local function writefile(filename, info)
    local wfile=io.open(filename, "w")
    assert(wfile)
    wfile:write(info)
    wfile:close()
end

local function is_dir(sPath)
    if type(sPath) ~= "string" then return false end

    local response = os.execute( "cd " .. sPath )
    if response == 0 then
        return true
    end
    return false
end

local file_exists = function(name)
    local f=io.open(name,"r")
   if f~=nil then io.close(f) return true else return false end
end

local area = nil 
local originalFile = ngx.var.file;
local index = string.find(ngx.var.uri, "([0-9]+)X([0-9]+)");
local indexw=string.find(ngx.var.uri, "watermark");
if index then
    area = string.sub(ngx.var.uri, index);
    index = string.find(area, "([.])");
    area = string.sub(area, 0, index-1);
        local index = string.find(originalFile, "([0-9]+)X([0-9]+)");
    originalFile = string.sub(originalFile, 0, index-2)
    originalFile = originalFile..'.jpg'

elseif indexw then
    local index = string.find(originalFile, "watermark");
    originalFile = string.sub(originalFile, 0, index-2)
    originalFile = originalFile..'.jpg'
end

-- 判断是否有原图片
if not file_exists(originalFile) then 
    writefile(originalFile, data)
end

local image_sizes = { "200X200","300X300", "400X400","800X800"};
function table.contains(table, element)
  for _, value in pairs(table) do
        if value == element then
            return true
        end
  end
  return false
end

if area and  table.contains(image_sizes, area) then

    local command = "gm convert ".. originalFile.." -thumbnail "..area.."! "..ngx.var.file;
   os.execute(command);
elseif indexw then
  local command ="gm composite -gravity southeast     /data/image/logo.png"..originalFile.." "..ngx.var.file;
      os.execute(command);
end;

if file_exists(ngx.var.file) then
      ngx.exec(ngx.var.uri)
else
      ngx.exit(404)
end