OpenResy+Lua 利用百度识图 将图片地址解析成文字
LUA代码:(注:LUA里有一个调用百度识图的接口IP:123.125.115.189(stu.baidu.com),不知为什么我的虚拟机无法解析stu.baidu.com,所以我只能PING出IP来用。)
location /test { content_by_lua ' local request_method = ngx.var.request_method; local args = nil; if "GET" == request_method then args = ngx.req.get_uri_args(); else ngx.req.read_body(); args = ngx.req.get_post_args(); end local imageUrl = args["imageUrl"] function Split(szFullString, szSeparator) local nFindStartIndex = 1 local nSplitIndex = 1 local nSplitArray = {} while true do local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex) if not nFindLastIndex then nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString)) break end nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1) nFindStartIndex = nFindLastIndex + string.len(szSeparator) nSplitIndex = nSplitIndex + 1 end return nSplitArray end local cjson = require "cjson" local http = require "resty.http" local hc = http:new() local ok, code, headers, status, body = hc:request { url = "http://123.125.115.189/n/pc_search?queryImageUrl="..imageUrl, method = "GET", -- POST or GET } local _,aaa = string.find(body,"keywords:\'") local bbb = string.find(body,"|default") local ccc = string.sub(body,aaa+2,bbb-2) ngx.say(tostring(ccc)) '; }
HTML代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>Untitled</title> <script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script> </head> <body> <input type="button" value = "test" id ="test" /> <input type="text" id ="imgUrl" /> <input type="button" value = "识图" id ="st" /> </body> <script> function unicode2Chr(str) { str=str.replace(/\\/g,"%"); return unescape(str); } $(function(){ $("#test").click(function(){ alert(); var str = "\x22\\u82f9\\u679c\x22,\x22\\u6307\\u6325\\u5927\\u5e08\x22,\x22\\u51fa\\u67dc\x22"; var code = str.replace(/\x22/g, "") alert(code); alert(unicode2Chr(code)); }); $("#st").click(function(){ var image_Url = $("#imgUrl").val(); $.ajax({ type : "POSST", async : false, url : "/test", data:{imageUrl:image_Url}, success : function(data) { var code = data.replace(/\\x22/g, "") alert(unicode2Chr(code).replace(/%/g, "")); } }); }); }); </script> </html>