1.接口说明
身份证OCR(API)定义:身份证OCR实现用户信息的自动识别和录入,应用于金融场景用户远程的身份认证,识别速度快,准确率高,减少用户输入成本,有效提高用户的体验。
1.1主要功能
身份证OCR接口能够准确识别照片文字信息并返回。其主要功能包括:
- 全信息识别:
- 返回姓名、身份证号、地址等结构化数据。
- 图像校正优化:
- 身份证头像、身份证图片自动裁剪并矫正。
- 低质量图像识别:
- 支持模糊、光照不均、透视畸变、复杂背景等低质量图像识别。
- 证件完整性检测:
- 智能检测证件完整性、遮盖度、复印件及翻拍检测。
- 高准确率:
- 识别准确率高达99+%,响应平均小于0.8秒,服务稳定。
- 多语言SDK:
- 提供多语言SDK及示例代码,免费在线测试效果。
1.2接入场景
支持各种程序和设备接入,包括小程序、APP、采集设备等,灵活适用于不同应用场景。
2.请求信息
2.1请求地址(URL)
POST http(s)://ocr-api.shiliuai.com/api/id_card_ocr/v2
2.2请求方式
POST
2.3请求头(header)
| 参数 | 类型 | 说明 |
|---|---|---|
| Authorization | string | 'APPCODE ' + 您的AppCode (注意英文空格) |
| Content-Type | string | application/json |
| 参数 | 类型 | 说明 |
|---|---|---|
| Content-Type | string | application/json |
| x-ca-key | string | 您的AppKey |
| x-ca-timestamp | string | 时间戳(毫秒) |
| x-ca-signature | string | 签名sign |
签名方法:
str = app_key×tamp&app_secret sign = md5(str)
2.4请求体(body)
| 参数 | 是否必填 | 类型 | 说明 |
|---|---|---|---|
| image_base64 | 必填 | string | base64编码的图片文件,像素范围:[15,8192],小于20M |
| return_rectified_card | 选填 | bool | 是否返回裁剪并矫正的身份证图片,默认为False |
| card_margin_ratio | 选填 | float | 裁剪时的边距比例,等于边距/长边,默认为0 |
| card_width | 选填 | int | 裁剪后的证件图片的宽度 |
| card_height | 选填 | int | 裁剪后的证件图片的高度(如果card_width和card_height都不传,或者都传-1,那么用原图中证件大小 如果其中一个>0, 另一个不传或传-1,那么表示该长度按比例缩放得到) |
| return_rectified_head | 选填 | bool | 是否返回裁剪并矫正的头像图片,默认为False,头像图片里,头顶和上边会有一些距离( 长宽比是441:358 ) |
| head_width | 选填 | int | 裁剪后的头像图片的宽度,如果head_width和head_height都不传,或者都传-1,那么用原图中头像大小,如果其中一个>0, 另一个不传或传-1,那么表示该长度按比例缩放得到 |
| head_height | 选填 | int | 裁剪后的头像图片的高度 |
3.返回信息
3.1返回类型
JSON
3.2返回码
| 参数名 | 类型 | 说明 |
|---|---|---|
| code | int | 返回码,0表示成功 |
| message | string | 返回信息 |
3.3返回信息
| 参数 | 参数类型 | 说明 |
|---|---|---|
| code | int | 错误码 |
| msg | string | 错误信息(英文) |
| msg_cn | string | 错误信息(中文) |
| success | bool | 识别是否成功 |
| image_id | string | 图片ID |
| request_id | string | 唯一请求ID |
| data | data | 具体看下面 |
3.3.1 data 信息
| 参数 | 参数类型 | 说明 | 举例 |
|---|---|---|---|
| is_front | bool | 是否正面 | |
| complete_score | float | 完整度[0, 1] | 0.8 |
| is_complete | bool | 是否完整,当complete_score==1时,为True | True |
| unoccluded_score | float | 无遮挡程度[0, 1] | |
| is_unoccluded | bool | 是否无遮挡,当unoccluded_score>0.99时,为True | |
| clear_score | float | [0, 1],清晰度,用文字可识别度计算 | 0.9 |
| is_clear | bool | 是否清晰,当clear_score>0.5时,为True | |
| rectified_card_base64 | string | 裁剪并矫正的身份证图片, 当return_rectified_card=True时有该项 | |
| rectified_head_base64 | string | 裁剪并矫正的头像图片, 当return_rectified_head=True且是正面时有该项 |
3.3.2 data 正面示例
| 参数 | 参数类型 | 说明 | 举例 |
|---|---|---|---|
| name | string | 姓名 | |
| sex | string | 性别 | 男 / 女 |
| ethnicity | string | 民族 | 汉 |
| birthDate | string | 出生日期 | 1999年1月10日 |
| address | string | 地址 | |
| idNumber | string | 身份证号 |
3.3.3 data 反面示例
| 参数 | 参数类型 | 说明 |
|---|---|---|
| authority | string | 签发机关 |
| validPeriod | string | 有效期限 |
3.4返回示例
{
"code": 200,
"msg": "success",
"msg_cn": "成功",
"success": true,
"image_id": "xxxx",
"request_id": "req_xxxx",
"data": {
"is_front": true,
"complete_score": 0.98,
"is_complete": true,
"clear_score": 0.92,
"is_clear": true,
"name": "张三",
"sex": "男",
"ethnicity": "汉",
"birthDate": "1990年01月01日",
"address": "北京市朝阳区XXX",
"idNumber": "110101199001011234"
}
}
3.5错误码
| 错误码 | 说明 |
|---|---|
| 200 | 成功 |
| 400 | 错误请求,比如参数错误 |
| 401 | 未经授权 |
| 403 | 禁止访问 |
| 429 | 请求过多 |
| 500 | 内部错误 |
| 604 | 接口停用 |
| 1001 | 服务异常,返回具体的错误原因 |
4.示例代码
4.1 Python
# -*- coding: utf-8 -*-
import requests
import base64
import json
# 请求接口
URL = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"
# 图片转base64
def get_base64(file_path):
with open(file_path, 'rb') as f:
data = f.read()
b64 = base64.b64encode(data).decode('utf8')
return b64
def demo(appcode, file_path):
# 请求头
headers = {
'Authorization': 'APPCODE %s' % appcode,
'Content-Type': 'application/json'
}
# 请求体
b64 = get_base64(file_path)
data = {"image_base64": b64}
# 请求
response = requests.post(url=URL, headers=headers, json=data)
content = json.loads(response.content)
print(content)
if __name__=="__main__":
appcode = "你的APPCODE"
file_path = "本地图片路径"
demo(appcode, file_path)
import requests
import base64
import json
import hashlib
import time
# 请求接口
URL = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"
# 图片转base64
def get_base64(file_path):
with open(file_path, 'rb') as f:
data = f.read()
b64 = base64.b64encode(data).decode('utf8')
return b64
# md5
def md5(s):
return hashlib.md5(s.encode("utf8")).hexdigest()
def demo(app_key, app_secret, file_path):
# 请求头
t = int(time.time() * 1000)
s = "%s&%s&%s" % (app_key, t, app_secret)
sign = md5(s)
headers = {
'x-ca-key': app_key,
'x-ca-timestamp': t,
'x-ca-signature': sign,
'Content-Type': 'application/json'
}
# 请求体
b64 = get_base64(file_path)
data = {"image_base64": b64}
# 请求
response = requests.post(url=URL, headers=headers, json=data)
content = json.loads(response.content)
print(content)
if __name__=="__main__":
app_key = "你的APP_KEY"
app_secret = "你的APP_SECRET"
file_path = "本地图片路径"
demo(app_key, app_secret, file_path)
4.2 PHP
// 图片转base64
function get_base64($path){
if($fp = fopen($path, "rb", 0)) {
$binary = fread($fp, filesize($path));
fclose($fp);
$b64 = base64_encode($binary);
}else{
$b64="";
printf("%s 文件不存在", $path);
}
return $b64;
}
// 请求接口
$url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2";
$appcode = "你的appcode";
$img_path = "图片路径";
$method = "POST";
// 请求头
$headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode);
array_push($headers, "Content-Type:application/json");
// 请求体
$b64 = get_base64($img_path);
$data = array(
"image_base64" => $b64
);
$post_data = json_encode($data);
// 请求
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($curl);
var_dump($result);
function get_base64($path){
if($fp = fopen($path, "rb", 0)) {
$binary = fread($fp, filesize($path)); // 文件读取
fclose($fp);
$b64 = base64_encode($binary); // 转base64
}else{
$b64="";
printf("%s 文件不存在", $path);
}
return $b64;
}
$url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2";
$img_path = "图片路径";
$method = "POST";
//请求头
$app_key = "你的app_key";
$app_secret = "你的app_secret";
$timestamp=time();
$sign_string = $app_key . "&" . $timestamp . "&" . $app_secret;
$sign = md5($sign_string);
$headers = array();
array_push($headers, "Content-Type:application/json");
array_push($headers, "x-ca-key:" . $app_key);
array_push($headers, "x-ca-timestamp:" . $timestamp);
array_push($headers, "x-ca-signature:" . $sign);
//请求体
$b64 = get_base64($img_path);
$data = array(
"image_base64" => $b64
);
$post_data = json_encode($data);
//请求
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($curl);
var_dump($result);
4.3 Java
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Base64;
public class Main {
public static String get_base64(String path) {
String b64 = "";
try {
// 使用Commons IO简化文件读取
byte[] content = FileUtils.readFileToByteArray(new File(path));
// 使用JDK自带的Base64
b64 = Base64.getEncoder().encodeToString(content);
} catch (IOException e) {
e.printStackTrace();
}
return b64;
}
public static void main(String[] args) {
String url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"; // 请求接口
String appcode = "你的APPCODE";
String imgFile = "本地图片路径";
Map headers = new HashMap<>();
headers.put("Authorization", "APPCODE " + appcode);
headers.put("Content-Type", "application/json");
// 请求体
JSONObject requestObj = new JSONObject();
requestObj.put("image_base64", get_base64(imgFile));
String bodys = requestObj.toString();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建POST请求
HttpPost httpPost = new HttpPost(url);
// 设置请求头
for (Map.Entry entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
// 设置请求体
StringEntity entity = new StringEntity(bodys, "UTF-8");
httpPost.setEntity(entity);
// 执行请求
HttpResponse response = httpClient.execute(httpPost);
int stat = response.getStatusLine().getStatusCode();
if (stat != 200) {
System.out.println("Http code: " + stat);
return;
}
String res = EntityUtils.toString(response.getEntity());
JSONObject res_obj = JSON.parseObject(res);
System.out.println(res_obj.toJSONString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Base64;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Demo {
public static String get_base64(String path) {
String b64="";
try {
File file = new File(path);
if (!file.exists()) {
System.err.println("文件不存在: " + path);
return b64;
}
byte[] content = FileUtils.readFileToByteArray(file);
b64 = Base64.getEncoder().encodeToString(content);
} catch (IOException e) {
System.err.println("读取文件失败: " + e.getMessage());
e.printStackTrace();
}
return b64;
}
public static String MD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1)
hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"; // 请求接口
String imgFile = "本地图片路径";
String app_key = "你的APPKEY";
String app_secret = "你的APPSECRET";
String timestamp = System.currentTimeMillis() + "";
String sign = MD5(app_key + "&" + timestamp + "&" + app_secret);
Map headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("x-ca-key", app_key);
headers.put("x-ca-timestamp", timestamp);
headers.put("x-ca-signature", sign);
JSONObject requestObj = new JSONObject();
requestObj.put("image_base64", get_base64(imgFile));
String bodys = requestObj.toString();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
for (Map.Entry entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
StringEntity entity = new StringEntity(bodys, "UTF-8");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
int stat = response.getStatusLine().getStatusCode();
if (stat != 200) {
System.out.println("Http code: " + stat);
System.out.println("Http " + EntityUtils.toString(response.getEntity()));
return;
}
String res = EntityUtils.toString(response.getEntity());
JSONObject res_obj = JSON.parseObject(res);
System.out.println(res_obj.toJSONString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.4 C#
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MyCSharpApp
{
public class Program
{
public static string GetBase64(string path)
{
string b64 = "";
try
{
// 读取文件内容
byte[] content = File.ReadAllBytes(path);
// 转换为Base64
b64 = Convert.ToBase64String(content);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return b64;
}
public static async Task Main(string[] args)
{
string url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"; // 请求接口
string appcode = "你的APPCODE";
string imgFile = "本地图片路径";
// 设置请求头
Dictionary headers = new Dictionary
{
{ "Authorization", "APPCODE " + appcode }
};
JObject requestObj = new JObject();
requestObj["image_base64"] = GetBase64(imgFile);
string body = requestObj.ToString();
try
{
using (HttpClient client = new HttpClient())
{
// 设置请求头
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
// 创建请求内容
StringContent content = new StringContent(body, Encoding.UTF8, "application/json");
// 发送请求并获取响应
HttpResponseMessage response = await client.PostAsync(url, content);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Http code: {(int)response.StatusCode}");
return;
}
// 读取响应内容
string responseContent = await response.Content.ReadAsStringAsync();
JObject resObj = JObject.Parse(responseContent);
Console.WriteLine(resObj.ToString(Formatting.Indented));
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MyCSharpApp
{
public class Program
{
public static string GetBase64(string path)
{
string b64 = "";
try
{
// 读取文件内容
byte[] content = File.ReadAllBytes(path);
// 转换为Base64
b64 = Convert.ToBase64String(content);
}
catch (Exception e)
{
Console.Error.WriteLine("读取文件失败: " + e.Message);
Console.WriteLine(e.Message);
}
return b64;
}
public static string CalculateMD5(string input)
{
try
{
// 创建MD5哈希提供程序
using (MD5 md5 = MD5.Create())
{
// 计算输入字符串的哈希值
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
// 将字节数组转换为十六进制字符串
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2"));
}
return sb.ToString();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return string.Empty; // 返回空字符串而不是null
}
}
public static async Task Main(string[] args)
{
string url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"; // 请求接口
string imgFile = "本地图片路径";
string app_key = "你的APPKEY";
string app_secret = "你的APPSECRET";
string timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString();
string sign = CalculateMD5(app_key + "&" + timestamp + "&" + app_secret);
// 设置请求头
Dictionary headers = new Dictionary
{
{ "x-ca-key", app_key },
{ "x-ca-timestamp", timestamp },
{ "x-ca-signature", sign }
};
// 请求体
JObject requestObj = new JObject();
requestObj["image_base64"] = GetBase64(imgFile);
string body = requestObj.ToString();
try
{
using (HttpClient client = new HttpClient())
{
// 设置请求头
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
// 创建请求内容
StringContent content = new StringContent(body, Encoding.UTF8, "application/json");
// 发送请求并获取响应
HttpResponseMessage response = await client.PostAsync(url, content);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Http code: {(int)response.StatusCode}");
Console.WriteLine($"Http {await response.Content.ReadAsStringAsync()}");
return;
}
// 读取响应内容
string responseContent = await response.Content.ReadAsStringAsync();
JObject resObj = JObject.Parse(responseContent);
Console.WriteLine(resObj.ToString(Formatting.Indented));
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
4.5 易语言
版本 2
.支持库 spec
.支持库 dp1
.子程序 身份证OCR识别_核心库版
.局部变量 局_网址, 文本型
.局部变量 局_方式, 整数型
.局部变量 局_提交数据, 文本型
.局部变量 局_提交协议头, 文本型
.局部变量 局_结果, 字节集
.局部变量 局_返回, 文本型
.局部变量 图片数据, 字节集
.局部变量 base64图片, 文本型
图片数据 = 读入文件 ("你的图片路径.jpg")
base64图片 = 编码_BASE64编码 (图片数据)
局_提交数据 = "{" + #引号 + "image_base64" + #引号 + ":" + #引号 + base64图片 + #引号 + "}"
局_网址 = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"
局_方式 = 1
局_提交协议头 = "Authorization: APPCODE 你的AppCode" + #换行符 + "Content-Type: application/json"
局_结果 = 网页_访问_对象 (局_网址, 局_方式, 局_提交数据, , , 局_提交协议头, , , , , , , , , , , , , )
局_返回 = 到文本 (编码_编码转换对象 (局_结果, , , ))
返回 (局_返回)
版本 2
.支持库 spec
.支持库 dp1
.子程序 身份证OCR识别_签名认证
.参数 app_key, 文本型
.参数 app_secret, 文本型
.参数 图片路径, 文本型
.局部变量 局_网址, 文本型
.局部变量 局_提交数据, 文本型
.局部变量 局_提交协议头, 文本型
.局部变量 局_结果, 字节集
.局部变量 局_返回, 文本型
.局部变量 图片数据, 字节集
.局部变量 base64图片, 文本型
.局部变量 时间戳, 文本型
.局部变量 签名字符串, 文本型
.局部变量 签名, 文本型
图片数据 = 读入文件 (图片路径)
base64图片 = 编码_BASE64编码 (图片数据)
时间戳 = 到文本 (时间_取时间戳 () * 1000)
签名字符串 = app_key + "&" + 时间戳 + "&" + app_secret
签名 = 到十六进制文本 (编码_MD5摘要 (到字节集 (签名字符串)))
局_提交数据 = "{" + #引号 + "image_base64" + #引号 + ":" + #引号 + base64图片 + #引号 + "}"
局_网址 = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"
局_提交协议头 = "x-ca-key: " + app_key + #换行符 + "x-ca-timestamp: " + 时间戳 + #换行符 + "x-ca-signature: " + 签名 + #换行符 + "Content-Type: application/json"
局_结果 = 网页_访问_对象 (局_网址, 1, 局_提交数据, , , 局_提交协议头, , , , , , , , , , , , , )
局_返回 = 到文本 (编码_编码转换对象 (局_结果, , , ))
返回 (局_返回)
4.6 天诺
public static string OCR_IDCard_Easy(Image image, string appcode)
{
string url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2";
var headers = new Dictionary
{
{"Authorization", "APPCODE " + appcode},
{"Content-Type", "application/json"}
};
string body = "{\"image_base64\":\"" + CustomHelp.ImageTobase64(image) + "\"}";
return CustomHelp.HttpPost(url, body, headers);
}
public static string app_key = "你的APPKEY";
public static string app_secret = "你的APPSECRET";
public static string GetTimestampMs()
{
return DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString();
}
public static string MD5(string input)
{
using (var md5 = System.Security.Cryptography.MD5.Create())
{
var bytes = System.Text.Encoding.UTF8.GetBytes(input);
var hash = md5.ComputeHash(bytes);
var sb = new System.Text.StringBuilder();
foreach (var b in hash) sb.Append(b.ToString("x2"));
return sb.ToString();
}
}
public static string OCR_IDCard(Image image)
{
string url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2";
string timestamp = GetTimestampMs();
string sign = MD5(app_key + "&" + timestamp + "&" + app_secret);
var headers = new Dictionary
{
{"x-ca-key", app_key},
{"x-ca-timestamp", timestamp},
{"x-ca-signature", sign},
{"Content-Type", "application/json"}
};
string body = "{\"image_base64\":\"" + CustomHelp.ImageTobase64(image) + "\"}";
return CustomHelp.HttpPost(url, body, headers);
}
4.7 按键精灵-电脑版
Import "Encrypt.dll"
VBSBegin
Function Base64Encode(filePath)
Set inStream = CreateObject("ADODB.Stream")
inStream.Type = 1
inStream.Open
inStream.LoadFromFile filePath
inStream.Position = 0
Set dom = CreateObject("MSXML2.DOMDocument")
Set elem = dom.createElement("tmp")
elem.dataType = "bin.base64"
elem.nodeTypedValue = inStream.Read
Base64Encode = elem.Text
inStream.Close
End Function
Function ocr_easy(appcode, imgPath)
url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"
jsonBody = "{""image_base64"":""" & Base64Encode(imgPath) & """}"
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "POST", url, False
http.setRequestHeader "Authorization", "APPCODE " & appcode
http.setRequestHeader "Content-Type", "application/json"
http.send jsonBody
ocr_easy = http.responseText
End Function
VBSEnd
appcode = "你的APPCODE"
res = ocr_easy(appcode, "你的图片路径.jpg")
TracePrint res
Import "Encrypt.dll"
VBSBegin
Function MD5(str)
MD5 = LCase(Encrypt.Md5String(str))
End Function
Function Base64Encode(filePath)
Set inStream = CreateObject("ADODB.Stream")
inStream.Type = 1
inStream.Open
inStream.LoadFromFile filePath
inStream.Position = 0
Set dom = CreateObject("MSXML2.DOMDocument")
Set elem = dom.createElement("tmp")
elem.dataType = "bin.base64"
elem.nodeTypedValue = inStream.Read
Base64Encode = elem.Text
inStream.Close
End Function
Function ocr_sign(appKey, appSecret, imgPath)
url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"
timestamp = CStr(DateDiff("s", "01/01/1970 00:00:00", Now()) * 1000)
signature = MD5(appKey & "&" & timestamp & "&" & appSecret)
jsonBody = "{""image_base64"":""" & Base64Encode(imgPath) & """}"
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "POST", url, False
http.setRequestHeader "x-ca-key", appKey
http.setRequestHeader "x-ca-timestamp", timestamp
http.setRequestHeader "x-ca-signature", signature
http.setRequestHeader "Content-Type", "application/json"
http.send jsonBody
ocr_sign = http.responseText
End Function
VBSEnd
appKey = "你的APPKEY"
appSecret = "你的APPSECRET"
res = ocr_sign(appKey, appSecret, "你的图片路径.jpg")
TracePrint res
4.8 按键精灵-手机版
Import "yd.luae"
Import "zm.luae"
Dim imagePath = "/sdcard/Pictures/test.png"
SnapShotEx imagePath
Function ocr_easy(appcode, imagePath)
Dim url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"
Dim body = "{""image_base64"":""" & yd.Base64EncodeFile(imagePath) & """}"
Dim headers = {null}
headers["Authorization"] = "APPCODE " & appcode
headers["Content-Type"] = "application/json"
Dim res = yd.HttpPost(url, body, headers)
ocr_easy = yd.JsonDecode(res)
End Function
Dim appcode = "你的 APPCODE"
Dim t1 = TickCount()
Dim res = ocr_easy(appcode, imagePath)
Dim t2 = TickCount()
TracePrint res["success"]
Import "yd.luae"
Import "zm.luae"
Dim imagePath = "/sdcard/Pictures/test.png"
SnapShotEx imagePath
Dim appKey = "你的 APPKEY"
Dim appSecret = "你的 APPSECRET"
Function ocr_sign(appKey, appSecret, imagePath)
Dim url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"
Dim timestamp = CStr(os.time()*1000)
Dim signature = Encode.Md5(appKey & "&" & timestamp & "&" & appSecret)
Dim body = "{""image_base64"":""" & yd.Base64EncodeFile(imagePath) & """}"
Dim headers = {null}
headers["x-ca-key"] = appKey
headers["x-ca-timestamp"] = timestamp
headers["x-ca-signature"] = signature
headers["Content-Type"] = "application/json"
Dim res = yd.HttpPost(url, body, headers)
ocr_sign = yd.JsonDecode(res)
End Function
Dim t1 = TickCount()
Dim res = ocr_sign(appKey, appSecret, imagePath)
Dim t2 = TickCount()
TracePrint res["success"]
4.9 触动精灵
require("tsnet")
require "TSLib"
local ts = require("ts")
local json = ts.json
function readFileBase64(path)
local f = io.open(path,"rb")
if not f then return nil end
local bytes = f:read("*all")
f:close()
return bytes:base64_encode()
end
function ocr_easy(appcode, imagePath)
local url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"
local body = json.encode({ image_base64 = readFileBase64(imagePath) })
local headers = {}
headers["Authorization"] = "APPCODE " .. appcode
headers["Content-Type"] = "application/json"
local resp = httpPost(url, body, { headers = headers })
return json.decode(resp)
end
require("tsnet")
require "TSLib"
local ts = require("ts")
local json = ts.json
function readFileBase64(path)
local f = io.open(path,"rb")
if not f then return nil end
local bytes = f:read("*all")
f:close()
return bytes:base64_encode()
end
function ocr_sign(appKey, appSecret, imagePath)
local url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"
local timestamp = tostring(os.time()*1000)
local signature = (appKey.."&"..timestamp.."&"..appSecret):md5()
local body = json.encode({ image_base64 = readFileBase64(imagePath) })
local headers = {}
headers["x-ca-key"] = appKey
headers["x-ca-timestamp"] = timestamp
headers["x-ca-signature"] = signature
headers["Content-Type"] = "application/json"
local resp = httpPost(url, body, { headers = headers })
return json.decode(resp)
end
local appKey = "你的 APPKEY"
local appSecret = "你的 APPSECRET"
local imagePath = userPath().."/test.jpg"
local w,h = getScreenSize()
snapshot(imagePath, 0, 0, w-1, h-1)
local t1 = ts.ms()
local res = ocr_sign(appKey, appSecret, imagePath)
local t2 = ts.ms()
nLog(res["success"])
4.10 懒人精灵
function ocr_easy(appcode, imagePath)
local url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"
local body = jsonLib.encode({ image_base64 = getFileBase64(imagePath) })
local headers = {}
headers["Authorization"] = "APPCODE " .. appcode
headers["Content-Type"] = "application/json"
local resp = httpPost(url, body, { headers = headers })
return jsonLib.decode(resp)
end
function ocr_sign(appKey, appSecret, imagePath)
local url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"
local timestamp = tostring(os.time()*1000)
local signature = MD5(appKey.."&"..timestamp.."&"..appSecret)
local body = jsonLib.encode({ image_base64 = getFileBase64(imagePath) })
local headers = {}
headers["x-ca-key"] = appKey
headers["x-ca-timestamp"] = timestamp
headers["x-ca-signature"] = signature
headers["Content-Type"] = "application/json"
local resp = httpPost(url, body, { headers = headers })
return jsonLib.decode(resp)
end
4.11 EasyClick
function main()
local request = image.requestScreenCapture(10000, 0)
if not request then
request = image.requestScreenCapture(10000, 0)
end
local appCode = "你的 APPCODE"
local img = image.captureFullScreenEx()
console.time("t")
local res = ocr_easy(appCode, img)
logd(console.timeEnd("t"))
logd(res.success)
end
function ocr_easy(appCode, img)
local url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"
local imgBase64 = image.toBase64Format(img, "jpg", 100)
image.recycle(img)
local body = JSON.stringify({ image_base64 = imgBase64 })
local params = {
url = url,
method = "POST",
headers = {
["Authorization"] = "APPCODE " .. appCode,
["Content-Type"] = "application/json"
},
requestBody = body
}
local res = http.request(params)
return JSON.parse(res.body)
end
function main()
local request = image.requestScreenCapture(10000, 0)
if not request then
request = image.requestScreenCapture(10000, 0)
end
local appKey = "你的 APPKEY"
local appSecret = "你的 APPSECRET"
local img = image.captureFullScreenEx()
console.time("t")
local res = ocr_sign(appKey, appSecret, img)
logd(console.timeEnd("t"))
logd(res.success)
end
function ocr_sign(appKey, appSecret, img)
local url = "https://ocr-api.shiliuai.com/api/id_card_ocr/v2"
local imgBase64 = image.toBase64Format(img, "jpg", 100)
local timestamp = tostring(os.time() * 1000)
local signature = utils.dataMd5(appKey .. "&" .. timestamp .. "&" .. appSecret)
image.recycle(img)
local body = JSON.stringify({ image_base64 = imgBase64 })
local params = {
url = url,
method = "POST",
headers = {
["x-ca-key"] = appKey,
["x-ca-timestamp"] = timestamp,
["x-ca-signature"] = signature,
["Content-Type"] = "application/json"
},
requestBody = body
}
local res = http.request(params)
return JSON.parse(res.body)
end