|
| 1 | +-- 写入文件 |
| 2 | +local function writefile(filename, info) |
| 3 | + local wfile=io.open(filename, "w") --写入文件(w覆盖) |
| 4 | + assert(wfile) --打开时验证是否出错 |
| 5 | + wfile:write(info) --写入传入的内容 |
| 6 | + wfile:close() --调用结束后记得关闭 |
| 7 | +end |
| 8 | + |
| 9 | +-- 检测路径是否目录 |
| 10 | +local function is_dir(sPath) |
| 11 | + if type(sPath) ~= "string" then return false end |
| 12 | + |
| 13 | + local response = os.execute( "cd " .. sPath ) |
| 14 | + if response == 0 then |
| 15 | + return true |
| 16 | + end |
| 17 | + return false |
| 18 | +end |
| 19 | + |
| 20 | +-- 检测文件是否存在 |
| 21 | +local file_exists = function(name) |
| 22 | + local f=io.open(name,"r") |
| 23 | + if f~=nil then io.close(f) return true else return false end |
| 24 | +end |
| 25 | + |
| 26 | +local area = nil |
| 27 | +local originalUri = ngx.var.uri; |
| 28 | +local originalFile = ngx.var.file; |
| 29 | +local index = string.find(ngx.var.uri, "([0-9]+)x([0-9]+)"); |
| 30 | +if index then |
| 31 | + originalUri = string.sub(ngx.var.uri, 0, index-2); |
| 32 | + area = string.sub(ngx.var.uri, index); |
| 33 | + index = string.find(area, "([.])"); |
| 34 | + area = string.sub(area, 0, index-1); |
| 35 | + |
| 36 | + local index = string.find(originalFile, "([0-9]+)x([0-9]+)"); |
| 37 | + originalFile = string.sub(originalFile, 0, index-2) |
| 38 | +end |
| 39 | + |
| 40 | +-- check original file |
| 41 | +if not file_exists(originalFile) then |
| 42 | + local fileid = string.sub(originalUri, 2); |
| 43 | + -- main |
| 44 | + local fastdfs = require('restyfastdfs') |
| 45 | + local fdfs = fastdfs:new() |
| 46 | + fdfs:set_tracker("112.124.106.166", 22121) |
| 47 | + fdfs:set_timeout(1000) |
| 48 | + fdfs:set_tracker_keepalive(0, 100) |
| 49 | + fdfs:set_storage_keepalive(0, 100) |
| 50 | + local data = fdfs:do_download(fileid) |
| 51 | + if data then |
| 52 | + -- check image dir |
| 53 | + if not is_dir(ngx.var.image_dir) then |
| 54 | + os.execute("mkdir -p " .. ngx.var.image_dir) |
| 55 | + end |
| 56 | + writefile(originalFile, data) |
| 57 | + end |
| 58 | +end |
| 59 | + |
| 60 | +-- 创建缩略图 |
| 61 | +local image_sizes = {"80x80", "800x600", "40x40", "60x60"}; |
| 62 | +function table.contains(table, element) |
| 63 | + for _, value in pairs(table) do |
| 64 | + if value == element then |
| 65 | + return true |
| 66 | + end |
| 67 | + end |
| 68 | + return false |
| 69 | +end |
| 70 | + |
| 71 | +if table.contains(image_sizes, area) then |
| 72 | + local command = "gm convert " .. originalFile .. " -thumbnail " .. area .. " -background gray -gravity center -extent " .. area .. " " .. ngx.var.file; |
| 73 | + os.execute(command); |
| 74 | +end; |
| 75 | + |
| 76 | +if file_exists(ngx.var.file) then |
| 77 | + --ngx.req.set_uri(ngx.var.uri, true); |
| 78 | + ngx.exec(ngx.var.uri) |
| 79 | +else |
| 80 | + ngx.exit(404) |
| 81 | +end |
0 commit comments