腾讯云身份证接口的调用
程序员文章站
2022-05-17 19:05:48
...
腾讯云提供的识别有两种方式:
1.ImageBase64
2.ImageUrl
两种都可以用,我们这里采用第一种方式:
首先写个方法,我们需要将上传的图片转换成base64格式:
public static String getBase64FromInputStream(InputStream in) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc=in.read(buff, 0, 100)) > 0){
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new String(Base64.encodeBase64(data));
}
然后,在controller层写一个方法来调用腾讯云提供的官方文档:
@RequestMapping("/idcd")
@ResponseBody
public String sfz(HttpServletRequest request,@RequestParam(value = "file") MultipartFile file){
try {
Credential cred = new Credential("你自己的**", "你自己的**");
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("ocr.tencentcloudapi.com");
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
OcrClient client = new OcrClient(cred, "ap-shanghai", clientProfile);
String base64FromInputStream = getBase64FromInputStream(file.getInputStream());
String params = "{\"ImageBase64\":\""+base64FromInputStream+"\",\"CardSide\":\"FRONT\"}";
//图片base64转换后传入参数中,cardside选择正面 FRONT
// Map params = new HashMap();
// params.put("ImageBase64",getBase64FromInputStream(file.getInputStream()));
// params.put("CardSide", "CardSide");
IDCardOCRRequest req = IDCardOCRRequest.fromJsonString(params, IDCardOCRRequest.class);
System.out.println(req.getConfig());
System.out.println(req.getImageBase64());
IDCardOCRResponse resp = client.IDCardOCR(req);
System.out.println(IDCardOCRRequest.toJsonString(resp));
}catch (Exception e){
e.printStackTrace();
}
return null;
}
然后我们在前台随便写一个上传图片的代码:
<form th:action="@{/book/idcd}" method="post" enctype="multipart/form-data">
<input type="file" name="file" ></br>
<input type="submit" value="提交"/>
</form>
选择一张准备好的身份证照片
{“Name”:“李明”,“Sex”:“男”,“Nation”:“汉”,“Birth”:“1985/4/10”,“Address”:“广东省深圳市南山区高新技术园腾讯大厦”,“IdNum”:“440305198504102577”,“Authority”:"",“ValidDate”:"",“AdvancedInfo”:"{}",“RequestId”:“3376a1a2-22c5-45d1-8481-0572c01cfc10”}
获取成功!
上一篇: WebApi Swagger基础上使用Sqlsugar
下一篇: 数据库系统学习(一)