身份证信息识别

调用阿里云实现身份证信息的识别

阿里云SDK

阿里云提供了身份证信息识别的java代码,先看源码,然后进行改写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package com.alibaba.ocr.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.api.gateway.demo.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.apache.commons.codec.binary.Base64.encodeBase64;



/**
* 使用APPCODE进行云市场ocr服务接口调用
*/

public class APPCodeDemo {

/*
* 获取参数的json对象
*/
public static JSONObject getParam(int type, String dataValue) {
JSONObject obj = new JSONObject();
try {
obj.put("dataType", type);
obj.put("dataValue", dataValue);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}

public static void main(String[] args){

String host = "http://dm-51.data.aliyun.com";
String path = "/rest/160601/ocr/ocr_idcard.json";
String appcode = "你的APPCODE";
String imgFile = "图片路径";
Boolean is_old_format = false;//如果文档的输入中含有inputs字段,设置为True, 否则设置为False
//请根据线上文档修改configure字段
JSONObject configObj = new JSONObject();
configObj.put("side", "face");
String config_str = configObj.toString();
// configObj.put("min_size", 5);
// String config_str = "";

String method = "POST";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);

Map<String, String> querys = new HashMap<String, String>();

// 对图像进行base64编码
String imgBase64 = "";
try {
File file = new File(imgFile);
byte[] content = new byte[(int) file.length()];
FileInputStream finputstream = new FileInputStream(file);
finputstream.read(content);
finputstream.close();
imgBase64 = new String(encodeBase64(content));
} catch (IOException e) {
e.printStackTrace();
return;
}
// 拼装请求body的json字符串
JSONObject requestObj = new JSONObject();
try {
if(is_old_format) {
JSONObject obj = new JSONObject();
obj.put("image", getParam(50, imgBase64));
if(config_str.length() > 0) {
obj.put("configure", getParam(50, config_str));
}
JSONArray inputArray = new JSONArray();
inputArray.add(obj);
requestObj.put("inputs", inputArray);
}else{
requestObj.put("image", imgBase64);
if(config_str.length() > 0) {
requestObj.put("configure", config_str);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
String bodys = requestObj.toString();

try {
/**
* 重要提示如下:
* HttpUtils请从
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
* 下载
*
* 相应的依赖请参照
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
*/
HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
int stat = response.getStatusLine().getStatusCode();
if(stat != 200){
System.out.println("Http code: " + stat);
System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message"));
System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
return;
}

String res = EntityUtils.toString(response.getEntity());
JSONObject res_obj = JSON.parseObject(res);
if(is_old_format) {
JSONArray outputArray = res_obj.getJSONArray("outputs");
String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
JSONObject out = JSON.parseObject(output);
System.out.println(out.toJSONString());
}else{
System.out.println(res_obj.toJSONString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

需求分析和代码改写

我们要把这个代码改写成工具类方便调用,这样controller里面的内容比较清晰明了。需求是,在注册的时候把身份证信息传上来,然后调用api进行身份证信息的识别,在注册的时候肯定是本地上传文件,所以前端过来的参数时multipartfile类型,我们要转换成base64类型(注意不要直接传base64作为参数类型,太长了,不允许)。

所以我们在controller里面调用工具类,把multipartfile类型转换成base64类型,工具类如下:

1
2
3
4
public static String MultipartFile2Base64(MultipartFile multipartFile) throws IOException {
byte[] byteArr = multipartFile.getBytes();
return new String(Base64.encodeBase64(byteArr));
}

现在controller里面已经得到了图片的base64编码,然后调用改写好的阿里云接口就行,改写之后的代码如下(提供了base64代码瞬间变得简洁):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package com.interest.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import java.util.HashMap;
import java.util.Map;

/**
* Description:
* 阿里云身份证识别服务接口调用
* @author HhZhu
* @date Created on 2020/4/1 16:50
*/
public class IdCardUtil {
/*
* 获取参数的json对象
*/
public static JSONObject getParam(int type, String dataValue) {
JSONObject obj = new JSONObject();
try {
obj.put("dataType", type);
obj.put("dataValue", dataValue);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}

public static String getMessage(String imgBase64){

String host = "";
String path = "";
String appcode = "";
Boolean is_old_format = false;//如果文档的输入中含有inputs字段,设置为True, 否则设置为False
//请根据线上文档修改configure字段
JSONObject configObj = new JSONObject();
//只识别正面,获取姓名存入数据库
configObj.put("side", "face");
String config_str = configObj.toString();
// configObj.put("min_size", 5);
// String config_str = "";

String method = "POST";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
Map<String, String> querys = new HashMap<String, String>();
// 拼装请求body的json字符串
JSONObject requestObj = new JSONObject();
try {
if(is_old_format) {
JSONObject obj = new JSONObject();
obj.put("image", getParam(50, imgBase64));
if(config_str.length() > 0) {
obj.put("configure", getParam(50, config_str));
}
JSONArray inputArray = new JSONArray();
inputArray.add(obj);
requestObj.put("inputs", inputArray);
}else{
requestObj.put("image", imgBase64);
if(config_str.length() > 0) {
requestObj.put("configure", config_str);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
String bodys = requestObj.toString();

try {
/**
* 重要提示如下:
* HttpUtils请从
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
* 下载
*
* 相应的依赖请参照
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
*/
HttpResponse response = HttpUtil.doPost(host, path, method, headers, querys, bodys);
int stat = response.getStatusLine().getStatusCode();
if(stat != 200){
System.out.println("Http code: " + stat);
System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message"));
System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
}

String res = EntityUtils.toString(response.getEntity());
JSONObject res_obj = JSON.parseObject(res);
if(is_old_format) {
JSONArray outputArray = res_obj.getJSONArray("outputs");
String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
JSONObject out = JSON.parseObject(output);
//System.out.println(out.toJSONString());
return out.toJSONString();
}else{
//System.out.println(res_obj.toJSONString());
return res_obj.toJSONString();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}

}

注意

  • 一是不要把base64编码直接作为参数

  • 二是调用接口返回的类型是一个String,要转换成对象才方便存取,工具类如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    public static Map<String, Object> json2Map(String jsonStr) {
    Map<String, Object> map = new HashMap<>();
    if(jsonStr != null && !"".equals(jsonStr)){
    //最外层解析
    JSONObject json = JSONObject.fromObject(jsonStr);
    for (Object k : json.keySet()) {
    Object v = json.get(k);
    //如果内层还是数组的话,继续解析
    if (v instanceof JSONArray) {
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    Iterator<JSONObject> it = ((JSONArray) v).iterator();
    while (it.hasNext()) {
    JSONObject json2 = it.next();
    list.add(json2Map(json2.toString()));
    }
    map.put(k.toString(), list);
    } else {
    map.put(k.toString(), v);
    }
    }
    return map;
    }else{
    return null;
    }
    }

    结果如下:

    image-20200409132248536

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

请我喝杯咖啡吧~

支付宝
微信