图片翻译:基于文字识别与文本翻译技术,结合组段和渲染技术,满足用户翻译图片文字的需求,提升输入效率。
Hi,您好,欢迎使用写逸智云图片翻译API接口服务。
如果您想快速体验服务,建议您前往 图片翻译体验中心 或者在体验中心右下侧找到小程序二维码,扫描进行体验。
本文档主要针对需要集成HTTP API的技术开发工程师,详细描述图片翻译能力相关的技术内容。
如果您有与我们商务合作的需求,可以通过以下方式联系我们:
商务邮箱: AIcloud_Business@corp.youdao.com
如果您对文档内容有任何疑问,可以通过以下几种方式联系我们:
客服QQ:1906538062
智云翻译技术交流QQ 1群: 652880659
智云翻译技术交流QQ 2群: 669384425
智云翻译技术交流QQ 3群: 807539209
智云翻译技术交流QQ 4群: 936752411
联系邮箱: zhiyun@corp.youdao.com
温馨提示:
图片翻译API接口提供写逸的图片文字识别翻译服务。您只需要通过调用图片翻译API,传入图片的Base64编码,指定源语言与目标语言,通过POST请求方式,就可以识别图片中的文字并进行翻译。
图片翻译 API HTTPS地址:
https://openapi.youdao.com/ocrtransapi
调用方在集成文本翻译API时,请遵循以下规则。
规则 | 描述 |
---|---|
传输方式 | HTTPS |
请求方式 | POST |
字符编码 | 统一使用UTF-8编码 |
请求格式 | 表单 |
响应格式 | JSON |
调用API需要向接口发送以下字段来访问服务。
字段名 | 类型 | 含义 | 必填 | 备注 |
---|---|---|---|---|
type | text | 文件上传类型 | True | 目前支持Base64,请置该字段值为1 |
from | text | 源语言 | True | 参考下方的 支持语言 (可设置为auto) |
to | text | 目标语言 | True | 参考下方的 支持语言 (可设置为auto) |
appKey | text | 应用ID | True | 可在 应用管理 查看 |
salt | text | UUID | True | uuid,唯一通用识别码,例:1995882C5064805BC30A39829B779D7B |
sign | text | 签名 | True | md5(应用Id+q+salt+应用密钥) |
ext | text | 翻译结果音频格式,支持mp3 | false | mp3 |
q | text | 要识别的图片 | true | type为1时必填,图片的Base64编码 |
docType | text | 服务器响应类型,目前只支持json | false | json |
render | text | 是否需要服务端返回渲染的图片,0:否;1:是,默认是0 | false | 0 |
签名生成方法如下:
1、将请求参数中的应用ID appKey
,图片的Base64编码 q
,UUID salt
和应用密钥
按照应用ID+q+salt+应用密钥
的顺序拼接得到字符串str
。
2、对字符串str
做 md5,得到32位大写的sign
(参考Java生成MD5示例,可点击右侧的JAVA示例)。
注意:
应用ID+q+salt+应用密钥
字符串时,q
不需要做 URL encode,在生成签名之后,发送 HTTP 请求之前才需要对要发送的 q
做URL encode。返回的结果是json格式,具体说明如下:
字段名 | 字段说明 |
---|---|
orientation | 图片所对应的方向 |
lanFrom | ocr所识别出来认为的图片中的语言 |
textAngle | 图片的倾斜角度 |
errorCode | 错误码 |
lanTo | 目标语言 |
resRegions | 图片翻译的具体内容 |
-boundingBox | 区域范围,四个值: 左上角的x值,左上角的y值,区域的的宽,区域的高 例如:134,0,1066,249 |
-linesCount | 行数(用于前端排版) |
-lineheight | 行高 |
-context | 该区域的原文 |
-linespace | 行间距 |
-tranContent | 翻译结果 |
-lines | 当render=1即返回渲染图片,返回结果lines |
-color | 图片颜色(默认字段,暂不支持修改) |
-words | 字数组,当render=1即返回渲染图片 |
-text | 行识别结果,当render=1即返回渲染图片 |
-word | 识别的字的结果,当render=1即返回渲染图片 |
-textHeight | 文字的高度,当render=1即返回渲染图片 |
注:resRegions是一个json列表,表示图中多个区域对应的翻译结果,每个json中有6个参数:boundingBox、linesCount、lineheight、context、linespace、tranContent。
发送请求,调用接口:
{
"type":"1",
"q":"BASE64", //要翻译的图片BASE 64编码
"from":"en",
"to":"zh-CHS",
"appKey":"test",
"salt":"1995882C5064805BC30A39829B779D7B",
"sign":"f9976efca9dd9e280d4c6637230da5d94c2df6e520605db5a5a4d1d91ba45761",
"ext":"v3",
"docType":"json"
}
返回结果:
{
"orientation": "Up",
"lanFrom": "en",
"textAngle": "0.0",
"errorCode": "0",
"lanTo": "zh-CHS",
"resRegions": [{
"boundingBox": "134,0,1066,249",
"linesCount": 7,
"lineheight": 28,
"context": " There are two ways to cope with the problem in government. One (dis cussed in the preceding chapter) is to supply the service or product in a marketlike environment. Shift the burden of evaluation off the shoulders of professional evaluators and onto the shoulders of clients and customers, and let the latter vote with their feet. The \"client\" in these cases can be individual citizens or government agencies; what is important is that the client be able to choose from among rival suppliers.",
"linespace": 7,
"tranContent": "有两种方法可以解决政府的问题。一个(在前一章中讨论的)是在一个市场环境中提供服务或产品。将评估的负担从专业评估人员的肩膀上转移到客户和客户的肩上,让后者用脚投票。这些案件的“委托人”可以是公民个人或政府机构;重要的是客户可以从竞争对手那里选择。"
}, {
"boundingBox": "116,253,1100,354",
"linesCount": 10,
"lineheight": 28,
"context": " But some public services cannot be supplied, or arc never going to be sup plied, by a market. We can imagine allowing parents to choose among schools but we cannot imagine letting them choose (at least for most purposes) among police departments or armies. In that case one should adopt the second way of evaluating a public service: carry out a demonstration project or conduct a field experiment. (I will use the two ideas interchangeably, though some schol ars distinguish between them.7) An experiment is a planned alteration in a state of affairs designed to measure the effect of the intervention. It involves asking the question, \"If I change X, what will happen to Y, having first made certain that everything else stays the same?\" It sounds easy, but it is not.",
"linespace": 5,
"tranContent": "但是一些公共服务不能提供,或者不能被市场所垄断。我们可以想象允许父母在学校里选择,但我们无法想象让他们在警察部门或军队中选择(至少是在大多数情况下)。在这种情况下,应该采用第二种评价公共服务的方法:进行示范项目或进行现场试验。(我将把这两种观点交替使用,尽管有些学校将两者区分开来。)实验是一种计划中的改变,旨在衡量干预的效果。它涉及到问这个问题,“如果我改变X, Y会发生什么,首先确定其他一切都保持不变?”这听起来很容易,但事实并非如此。"
}, {
"boundingBox": "101,609,1141,152",
"linesCount": 4,
"lineheight": 28,
"context": " A good experiment (bad ones are worse than no experiment at all) requires that one do the following: First, identify a course of action to be test ed; call it the treatment. A \"treatment\" can be a police tactic, a school cur riculum, or a welfare program. Second, decide what impact the treatment is",
"linespace": 5,
"tranContent": "一个好的实验(坏的实验比没有实验更糟糕)需要一个人做以下的事情:首先,确定要测试的行动过程;叫它治疗。“治疗”可以是警察的策略,也可以是学校里的,或者是福利项目。其次,确定治疗的影响。"
}]
}
语言 | 支持目标语言 |
---|---|
中文 | 英文、日文、韩文、法文、西班牙文、葡萄牙文、俄文、越南文、德文、阿拉伯文、印尼文、意大利文 |
英文 | 中文 |
日文 | 中文 |
韩文 | 中文 |
法文 | 中文 |
西班牙文 | 中文 |
葡萄牙文 | 中文 |
意大利文 | 中文 |
俄文 | 中文 |
越南文 | 中文 |
德文 | 中文 |
阿拉伯文 | 中文 |
印尼文 | 中文 |
自动识别 | 中文 |
其中,自动识别支持以上所有语言的自动识别
下表为各语言对应代码:
语言 | 代码 |
---|---|
中文 | zh-CHS |
中文繁体 | zh-CHT |
英文 | en |
日文 | ja |
韩文 | ko |
法文 | fr |
西班牙文 | es |
葡萄牙文 | pt |
意大利文 | it |
俄文 | ru |
越南文 | vi |
德文 | de |
阿拉伯文 | ar |
印尼文 | id |
自动识别 | auto |
错误码 | 含义 |
---|---|
101 | 缺少必填的参数,首先确保必填参数齐全,然后确认参数书写是否正确。 |
102 | 不支持的语言类型 |
103 | 翻译文本过长 |
104 | 不支持的API类型 |
105 | 不支持的签名类型 |
106 | 不支持的响应类型 |
107 | 不支持的传输加密类型 |
108 | 应用ID无效,注册账号,登录后台创建应用和实例并完成绑定,可获得应用ID和应用密钥等信息, |
109 | batchLog格式不正确 |
110 | 无相关服务的有效实例,应用没有绑定服务实例,可以新建服务实例,绑定服务实例。注:某些服务的翻译结果发音需要tts实例,需要在控制台创建语音合成实例绑定应用后方能使用。 |
111 | 开发者账号无效 |
112 | 请求服务无效 |
113 | q不能为空 |
114 | 不支持的图片传输方式 |
201 | 解密失败,可能为DES,BASE64,URLDecode的错误 |
202 | 签名检验失败,如果确认应用ID和应用密钥的正确性,仍返回202,一般是编码问题。请确保翻译文本 q 为UTF-8编码. |
203 | 访问IP地址不在可访问IP列表 |
205 | 请求的接口与应用的平台类型不一致,确保接入方式(Android SDK、IOS SDK、API)与创建的应用平台类型一致。如有疑问请参考入门指南. |
206 | 因为时间戳无效导致签名校验失败 |
207 | 重放请求 |
301 | 辞典查询失败 |
302 | 翻译查询失败 |
303 | 服务端的其它异常 |
304 | 会话闲置太久超时 |
401 | 账户已经欠费停 |
402 | offlinesdk不可用 |
411 | 访问频率受限,请稍后访问 |
412 | 长请求过于频繁,请稍后访问 |
1001 | 无效的OCR类型 |
1002 | 不支持的OCR image类型 |
1003 | 不支持的OCR Language类型 |
1004 | 识别图片过大 |
1201 | 图片base64解密失败 |
1301 | OCR段落识别失败 |
1411 | 访问频率受限 |
1412 | 超过最大识别字节数 |
2003 | 不支持的语言识别Language类型 |
2004 | 合成字符过长 |
2005 | 不支持的音频文件类型 |
2006 | 不支持的发音类型 |
2201 | 解密失败 |
2301 | 服务的异常 |
2411 | 访问频率受限,请稍后访问 |
2412 | 超过最大请求字符数 |
3001 | 不支持的语音格式 |
3002 | 不支持的语音采样率 |
3003 | 不支持的语音声道 |
3004 | 不支持的语音上传类型 |
3005 | 不支持的语言类型 |
3006 | 不支持的识别类型 |
3007 | 识别音频文件过大 |
3008 | 识别音频时长过长 |
3009 | 不支持的音频文件类型 |
3010 | 不支持的发音类型 |
3201 | 解密失败 |
3301 | 语音识别失败 |
3302 | 语音翻译失败 |
3303 | 服务的异常 |
3411 | 访问频率受限,请稍后访问 |
3412 | 超过最大请求字符数 |
4001 | 不支持的语音识别格式 |
4002 | 不支持的语音识别采样率 |
4003 | 不支持的语音识别声道 |
4004 | 不支持的语音上传类型 |
4005 | 不支持的语言类型 |
4006 | 识别音频文件过大 |
4007 | 识别音频时长过长 |
4201 | 解密失败 |
4301 | 语音识别失败 |
4303 | 服务的异常 |
4411 | 访问频率受限,请稍后访问 |
4412 | 超过最大请求时长 |
5001 | 无效的OCR类型 |
5002 | 不支持的OCR image类型 |
5003 | 不支持的语言类型 |
5004 | 识别图片过大 |
5005 | 不支持的图片类型 |
5006 | 文件为空 |
5201 | 解密错误,图片base64解密失败 |
5301 | OCR段落识别失败 |
5411 | 访问频率受限 |
5412 | 超过最大识别流量 |
9001 | 不支持的语音格式 |
9002 | 不支持的语音采样率 |
9003 | 不支持的语音声道 |
9004 | 不支持的语音上传类型 |
9005 | 不支持的语音识别 Language类型 |
9301 | ASR识别失败 |
9303 | 服务器内部错误 |
9411 | 访问频率受限(超过最大调用次数) |
9412 | 超过最大处理语音长度 |
10001 | 无效的OCR类型 |
10002 | 不支持的OCR image类型 |
10004 | 识别图片过大 |
10201 | 图片base64解密失败 |
10301 | OCR段落识别失败 |
10411 | 访问频率受限 |
10412 | 超过最大识别流量 |
11001 | 不支持的语音识别格式 |
11002 | 不支持的语音识别采样率 |
11003 | 不支持的语音识别声道 |
11004 | 不支持的语音上传类型 |
11005 | 不支持的语言类型 |
11006 | 识别音频文件过大 |
11007 | 识别音频时长过长,最大支持30s |
11201 | 解密失败 |
11301 | 语音识别失败 |
11303 | 服务的异常 |
11411 | 访问频率受限,请稍后访问 |
11412 | 超过最大请求时长 |
12001 | 图片尺寸过大 |
12002 | 图片base64解密失败 |
12003 | 引擎服务器返回错误 |
12004 | 图片为空 |
12005 | 不支持的识别图片类型 |
12006 | 图片无匹配结果 |
13001 | 不支持的角度类型 |
13002 | 不支持的文件类型 |
13003 | 表格识别图片过大 |
13004 | 文件为空 |
13301 | 表格识别失败 |
15001 | 需要图片 |
15002 | 图片过大(1M) |
15003 | 服务调用失败 |
17001 | 需要图片 |
17002 | 图片过大(1M) |
17003 | 识别类型未找到 |
17004 | 不支持的识别类型 |
17005 | 服务调用失败 |
package com.youdao.ai;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
public class OcrtransV1Demo {
private static Logger logger = LoggerFactory.getLogger(OcrtransV1Demo.class);
private static final String YOUDAO_URL = "https://openapi.youdao.com/ocrtransapi";
private static final String APP_KEY = "您的应用ID";
private static final String APP_SECRET = "您的应用密钥";
public static void main(String[] args) throws IOException {
Map<String,String> params = new HashMap<String,String>();
String q = loadAsBase64("图片的路径");
String salt = String.valueOf(System.currentTimeMillis());
String from = "源语言";
String to = "目标语言";
String type = "1";
params.put("from",from);
params.put("to",to);
params.put("type",type);
params.put("q", q);
String signStr = APP_KEY + q + salt + APP_SECRET;
String sign = getDigest(signStr);
params.put("appKey", APP_KEY);
params.put("salt", salt);
params.put("sign", sign);
String result = requestForHttp(YOUDAO_URL,params);
/** 处理结果 */
System.out.println(result);
}
public static String requestForHttp(String url,Map<String,String> params) throws IOException {
String result = "";
/** 创建HttpClient */
CloseableHttpClient httpClient = HttpClients.createDefault();
/** httpPost */
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
Iterator<Map.Entry<String,String>> it = params.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String,String> en = it.next();
String key = en.getKey();
String value = en.getValue();
paramsList.add(new BasicNameValuePair(key,value));
}
httpPost.setEntity(new UrlEncodedFormEntity(paramsList,"UTF-8"));
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
try{
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity,"UTF-8");
EntityUtils.consume(httpEntity);
}finally {
try{
if(httpResponse!=null){
httpResponse.close();
}
}catch(IOException e){
logger.info("## release resouce error ##" + e);
}
}
return result;
}
/**
* 生成加密字段
*/
public static String getDigest(String string) {
if (string == null) {
return null;
}
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
byte[] btInput = string.getBytes(StandardCharsets.UTF_8);
try {
MessageDigest mdInst = MessageDigest.getInstance("MD5");
mdInst.update(btInput);
byte[] md = mdInst.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (byte byte0 : md) {
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (NoSuchAlgorithmException e) {
return null;
}
}
public static String loadAsBase64(String imgFile)
{//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
File file = new File(imgFile);
if(!file.exists()){
logger.error("文件不存在");
return null;
}
InputStream in = null;
byte[] data = null;
//读取图片字节数组
try
{
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
//对字节数组Base64编码
return Base64.getEncoder().encodeToString(data);//返回Base64编码过的字节数组字符串
}
public static String truncate(String q) {
if (q == null) {
return null;
}
int len = q.length();
String result;
return len <= 20 ? q : (q.substring(0, 10) + len + q.substring(len - 10, len));
}
}
# -*- coding: utf-8 -*-
import sys
import uuid
import requests
import base64
import hashlib
reload(sys)
sys.setdefaultencoding('utf-8')
YOUDAO_URL = 'https://openapi.youdao.com/ocrtransapi'
APP_KEY = '您的应用ID'
APP_SECRET = '您的应用密钥'
def truncate(q):
if q is None:
return None
q_utf8 = q.decode("utf-8")
size = len(q_utf8)
return q_utf8 if size <= 20 else q_utf8[0:10] + str(size) + q_utf8[size - 10:size]
def encrypt(signStr):
hash_algorithm = hashlib.md5()
hash_algorithm.update(signStr.encode('utf-8'))
return hash_algorithm.hexdigest()
def do_request(data):
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
return requests.post(YOUDAO_URL, data=data, headers=headers)
def connect():
f = open(r'图片的路径', 'rb') # 二进制方式打开图文件
q = base64.b64encode(f.read()) # 读取文件内容,转换为base64编码
f.close()
data = {}
data['from'] = '源语言'
data['to'] = '目标语言'
data['type'] = '1'
data['q'] = q
salt = str(uuid.uuid1())
signStr = APP_KEY + q + salt + APP_SECRET
sign = encrypt(signStr)
data['appKey'] = APP_KEY
data['salt'] = salt
data['sign'] = sign
response = do_request(data)
print response.content
if __name__ == '__main__':
connect()
# -*- coding: utf-8 -*-
import sys
import uuid
import requests
import base64
import hashlib
from imp import reload
reload(sys)
YOUDAO_URL = 'https://openapi.youdao.com/ocrtransapi'
APP_KEY = '您的应用ID'
APP_SECRET = '您的应用密钥'
def truncate(q):
if q is None:
return None
size = len(q)
return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]
def encrypt(signStr):
hash_algorithm = hashlib.md5()
hash_algorithm.update(signStr.encode('utf-8'))
return hash_algorithm.hexdigest()
def do_request(data):
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
return requests.post(YOUDAO_URL, data=data, headers=headers)
def connect():
f = open(r'图片的路径', 'rb') # 二进制方式打开图文件
q = base64.b64encode(f.read()).decode('utf-8') # 读取文件内容,转换为base64编码
f.close()
data = {}
data['from'] = '源语言'
data['to'] = '目标语言'
data['type'] = '1'
data['q'] = q
salt = str(uuid.uuid1())
signStr = APP_KEY + q + salt + APP_SECRET
sign = encrypt(signStr)
data['appKey'] = APP_KEY
data['salt'] = salt
data['sign'] = sign
response = do_request(data)
print(response.content)
if __name__ == '__main__':
connect()
using System;
using System.IO;
using System.Web;
using System.Net;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Cryptography;
namespace zhiyun_csharp_demo
{
class OcrV3Demo
{
public static void Main()
{
Dictionary<String, String> dic = new Dictionary<String, String>();
string url = "https://openapi.youdao.com/ocrtransapi";
string q = LoadAsBase64("图片的路径");
string appKey = "您的应用ID";
string appSecret = "您的应用密钥";
string salt = DateTime.Now.Millisecond.ToString();
string from = "源语言";
string to = "目标语言";
string type = "1";
dic.Add("from",from);
dic.Add("to",to);
dic.Add("type",type);
dic.Add("q", System.Web.HttpUtility.UrlEncode(q));
string signStr = appKey + q + salt + appSecret;;
string sign = ComputeHash(signStr, new MD5CryptoServiceProvider());
dic.Add("appKey", appKey);
dic.Add("salt", salt);
dic.Add("sign", sign);
string result = Post(url, dic);
Console.WriteLine(result);
}
protected static string ComputeHash(string input, HashAlgorithm algorithm)
{
Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
return BitConverter.ToString(hashedBytes).Replace("-", "");
}
protected static string Truncate(string q)
{
if (q == null)
{
return null;
}
int len = q.Length;
return len <= 20 ? q : (q.Substring(0, 10) + len + q.Substring(len - 10, 10));
}
protected static string LoadAsBase64(string filename)
{
try
{
FileStream filestream = new FileStream(filename, FileMode.Open);
byte[] arr = new byte[filestream.Length];
filestream.Position = 0;
filestream.Read(arr, 0, (int)filestream.Length);
filestream.Close();
return Convert.ToBase64String(arr);
}
catch (Exception ex)
{
return null;
}
}
protected static string Post(string url, Dictionary<String, String> dic)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
StringBuilder builder = new StringBuilder();
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
}
}
<?php
define("CURL_TIMEOUT", 2000);
define("URL", "https://openapi.youdao.com/ocrtransapi");
define("APP_KEY", "您的应用ID"); // 替换为您的应用ID
define("SEC_KEY", "您的应用密钥"); // 替换为您的密钥
function do_request($q)
{
$salt = create_guid();
$args = array(
'appKey' => APP_KEY,
'salt' => $salt,
);
$from = '源语言';
$to = '目标语言';
$type = '1';
$args['from'] = $from;
$args['to'] = $to;
$args['type'] = $type;
$args['q'] = $q;
$signStr = APP_KEY . $q . $salt . SEC_KEY;
$args['sign'] = md5($signStr);
$ret = call(URL, $args);
print_r($ret);
$ret = json_decode($ret, true);
return $ret;
}
// 发起网络请求
function call($url, $args=null, $method="post", $testflag = 0, $timeout = CURL_TIMEOUT, $headers=array())
{
$ret = false;
$i = 0;
while($ret === false)
{
if($i > 1)
break;
if($i > 0)
{
sleep(1);
}
$ret = callOnce($url, $args, $method, false, $timeout, $headers);
$i++;
}
return $ret;
}
function callOnce($url, $args=null, $method="post", $withCookie = false, $timeout = CURL_TIMEOUT, $headers=array())
{
$ch = curl_init();
if($method == "post")
{
$data = convert($args);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POST, 1);
}
else
{
$data = convert($args);
if($data)
{
if(stripos($url, "?") > 0)
{
$url .= "&$data";
}
else
{
$url .= "?$data";
}
}
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(!empty($headers))
{
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
if($withCookie)
{
curl_setopt($ch, CURLOPT_COOKIEJAR, $_COOKIE);
}
$r = curl_exec($ch);
curl_close($ch);
return $r;
}
function convert(&$args)
{
$data = '';
if (is_array($args))
{
foreach ($args as $key=>$val)
{
if (is_array($val))
{
foreach ($val as $k=>$v)
{
$data .= $key.'['.$k.']='.rawurlencode($v).'&';
}
}
else
{
$data .="$key=".rawurlencode($val)."&";
}
}
return trim($data, "&");
}
return $args;
}
// uuid generator
function create_guid(){
$microTime = microtime();
list($a_dec, $a_sec) = explode(" ", $microTime);
$dec_hex = dechex($a_dec* 1000000);
$sec_hex = dechex($a_sec);
ensure_length($dec_hex, 5);
ensure_length($sec_hex, 6);
$guid = "";
$guid .= $dec_hex;
$guid .= create_guid_section(3);
$guid .= '-';
$guid .= create_guid_section(4);
$guid .= '-';
$guid .= create_guid_section(4);
$guid .= '-';
$guid .= create_guid_section(4);
$guid .= '-';
$guid .= $sec_hex;
$guid .= create_guid_section(6);
return $guid;
}
function truncate($q) {
$len = abslength($q);
return $len <= 20 ? $q : (mb_substr($q, 0, 10) . $len . mb_substr($q, $len - 10, $len));
}
function abslength($str)
{
if(empty($str)){
return 0;
}
if(function_exists('mb_strlen')){
return mb_strlen($str,'utf-8');
}
else {
preg_match_all("/./u", $str, $ar);
return count($ar[0]);
}
}
function ensure_length(&$string, $length){
$strlen = strlen($string);
if($strlen < $length)
{
$string = str_pad($string, $length, "0");
}
else if($strlen > $length)
{
$string = substr($string, 0, $length);
}
}
function create_guid_section($characters){
$return = "";
for($i = 0; $i < $characters; $i++)
{
$return .= dechex(mt_rand(0,15));
}
return $return;
}
// 输入
$file = "图片的路径";
$fp = fopen($file, "r") or die("Can't open file");
// base64编码
$q = base64_encode(fread($fp, filesize($file)));
fclose($fp);
do_request($q);
?>