java实现身份证识别
程序员文章站
2022-03-10 18:37:44
第一步:准备工作我们这里调用的是百度的身份证识别api,我们可以在百度的api里申请这个api权限每天有500次调用机会网站申请地址:https://ai.baidu.com/ 需要用到我们的API Key Secret Key 请保存好第二部:Java后端编写代码并解析数据@RequestMapping(value = "getCardMessage",method = RequestMethod.POST)@ResponseBodypublic String baiDuCard(@...
第一步:准备工作
我们这里调用的是百度的身份证识别api,我们可以在百度的api里申请这个api权限每天有500次调用机会
网站申请地址:https://ai.baidu.com/ 需要用到我们的API Key Secret Key 请保存好
第二部:Java后端编写代码并解析数据
@RequestMapping(value = "getCardMessage",method = RequestMethod.POST)
@ResponseBody
public String baiDuCard(@RequestBody String file){
String auth = BaiDuCardIdentification.getAuth("API Key","Secret Key");//获取access_token
JSONObject parseObject = JSONObject.parseObject(file);//将字符串转换为json对象
Object object = parseObject.get("direction"); //获取你上传的身份证是照片面还是国徽面 front 照片面 back 国徽面
//照片面和国徽面百度返回的数据是不一样的 要注意 做好数据的解析
if (object.toString().equals("front")) {//比较如果是照片面进行处理数据
//识别身份证信息 是要传入的两个参数 一个是access_token 另一个是文件的路径
String idcard = BaiDuCardIdentification.idcard(auth, parseObject.get("file").toString());
JSONObject parse = JSONObject.parseObject(idcard); //将百度返回给我们的身份证信息 转换为json对象
String idcard_number_type = parse.get("idcard_number_type").toString();//获取idcard_number_type判断身份证是否合法
if (idcard.contains("edit_tool")) {//如果你的身份证图片被修改过 会返回这个字段 值为哪一个软件编辑过
return ResultJsonData.resultFailed("身份证被"+parse.get("edit_tool").toString()+"编辑过,请重新上传");
}
if (parse.get("image_status").toString().equals("non_idcard")) {//判断你上传的这张图片是否是个身份证图片
return ResultJsonData.resultFailed("身份证不合格,请上传身份证照片面图片");
}
if (idcard_number_type.equals("1")) {//只有idcard_number_type值为1的时候是合格的 其他的均为不合格
return ResultJsonData.resultData(0, "身份证识别成功",parse);
}
//身份证不合格的就返回它的错误码 可以到官方文档查看具体的错误类型
return ResultJsonData.resultFailed("身份证不合法错误码为:"+idcard_number_type);
}
if (object.toString().equals("back")) {//比较如果是国徽面进行处理数据
//识别身份证信息 是要传入的两个参数 一个是access_token 另一个是文件的路径
String idcard = BaiDuCardIdentification.idcard(auth, parseObject.get("file").toString());
JSONObject parse = JSONObject.parseObject(idcard);//将百度返回给我们的身份证信息 转换为json对象
if (parse.get("image_status").toString().equals("non_idcard")) {//判断你上传的这张图片是否是个身份证图片
return ResultJsonData.resultFailed("身份证不合格,请上传身份证国徽面图片");
}
return ResultJsonData.resultData(0,"身份证识别成功",parse);
}
return null;
}
接口使用到的方法:(对方法进行了分离)
public static String idcard(String accessToken,String filePath) {
// 请求url
String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
try {
// 本地文件路径
byte[] imgData = FileUtil.readFileByBytes(filePath); //转换为字节
String imgStr = Base64Util.encode(imgData);//对图片进行base64的编码
String imgParam = URLEncoder.encode(filePath, "UTF-8");//对图片路径进行url编码 是必须的
//detect_risk默认为false不验证身份证的真伪,值为true的时候验证身份证的真伪
String param = "id_card_side=" + "front" + "&url=" + imgParam+"&detect_risk="+"true";
String result = HttpUtil.post(url, accessToken, param); //用到的工具类
System.out.println(result);
return result;
} catch (Exception e) {
return ResultJsonData.resultFailed("身份证识别次数没有了,请联系管理员");
}
}
public static String getAuth(String ak, String sk) {
// 获取token地址
String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
String getAccessTokenUrl = authHost
// 1. grant_type为固定参数
+ "grant_type=client_credentials"
// 2. 官网获取的 API Key
+ "&client_id=" + ak
// 3. 官网获取的 Secret Key
+ "&client_secret=" + sk;
try {
URL realUrl = new URL(getAccessTokenUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
connection.setRequestMethod("GET");//设置请求方式
connection.connect();//发送url
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.err.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String result = "";
String line;
while ((line = in.readLine()) != null) {
result += line;
}
/**
* 返回结果示例
*/
JSONObject jsonObject = new JSONObject(result);
String access_token = jsonObject.getString("access_token");
return access_token;
} catch (Exception e) {
return ResultJsonData.resultFailed("获取token失败");
}
}
java用到的工具类
JSON 工具类
package com.zhonggu.crm.utils.BaiDu;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
/**
* Json工具类.
*/
public class GsonUtils {
private static Gson gson = new GsonBuilder().create();
public static String toJson(Object value) {
return gson.toJson(value);
}
public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException {
return gson.fromJson(json, classOfT);
}
public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException {
return (T) gson.fromJson(json, typeOfT);
}
}
http 工具类
package com.zhonggu.crm.utils.BaiDu;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* http 工具类
*/
public class HttpUtil {
public static String post(String requestUrl, String accessToken, String params)
throws Exception {
String contentType = "application/x-www-form-urlencoded";
return HttpUtil.post(requestUrl, accessToken, contentType, params);
}
public static String post(String requestUrl, String accessToken, String contentType, String params)
throws Exception {
String encoding = "UTF-8";
if (requestUrl.contains("nlp")) {
encoding = "GBK";
}
return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
}
public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
throws Exception {
String url = requestUrl + "?access_token=" + accessToken;
return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
}
public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
throws Exception {
URL url = new URL(generalUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 设置通用的请求属性
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
// 得到请求的输出流对象
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(params.getBytes(encoding));
out.flush();
out.close();
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> headers = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : headers.keySet()) {
System.err.println(key + "--->" + headers.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = null;
in = new BufferedReader(
new InputStreamReader(connection.getInputStream(), encoding));
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
in.close();
System.err.println("result:" + result);
return result;
}
}
文件读取 工具类
package com.zhonggu.crm.utils.BaiDu;
import java.io.*;
/**
* 文件读取工具类
*/
public class FileUtil {
/**
* 读取文件内容,作为字符串返回
*/
public static String readFileAsString(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
}
if (file.length() > 1024 * 1024 * 1024) {
throw new IOException("File is too large");
}
StringBuilder sb = new StringBuilder((int) (file.length()));
// 创建字节输入流
FileInputStream fis = new FileInputStream(filePath);
// 创建一个长度为10240的Buffer
byte[] bbuf = new byte[10240];
// 用于保存实际读取的字节数
int hasRead = 0;
while ( (hasRead = fis.read(bbuf)) > 0 ) {
sb.append(new String(bbuf, 0, hasRead));
}
fis.close();
return sb.toString();
}
/**
* 根据文件路径读取byte[] 数组
*/
public static byte[] readFileByBytes(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
short bufSize = 1024;
byte[] buffer = new byte[bufSize];
int len1;
while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
bos.write(buffer, 0, len1);
}
byte[] var7 = bos.toByteArray();
return var7;
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException var14) {
var14.printStackTrace();
}
bos.close();
}
}
}
}
Base64转换 工具类
package com.zhonggu.crm.utils.BaiDu;
/**
* Base64 工具类
*/
public class Base64Util {
private static final char last2byte = (char) Integer.parseInt("00000011", 2);
private static final char last4byte = (char) Integer.parseInt("00001111", 2);
private static final char last6byte = (char) Integer.parseInt("00111111", 2);
private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
public Base64Util() {
}
public static String encode(byte[] from) {
StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
int num = 0;
char currentByte = 0;
int i;
for (i = 0; i < from.length; ++i) {
for (num %= 8; num < 8; num += 6) {
switch (num) {
case 0:
currentByte = (char) (from[i] & lead6byte);
currentByte = (char) (currentByte >>> 2);
case 1:
case 3:
case 5:
default:
break;
case 2:
currentByte = (char) (from[i] & last6byte);
break;
case 4:
currentByte = (char) (from[i] & last4byte);
currentByte = (char) (currentByte << 2);
if (i + 1 < from.length) {
currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
}
break;
case 6:
currentByte = (char) (from[i] & last2byte);
currentByte = (char) (currentByte << 4);
if (i + 1 < from.length) {
currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
}
}
to.append(encodeTable[currentByte]);
}
}
if (to.length() % 4 != 0) {
for (i = 4 - to.length() % 4; i > 0; --i) {
to.append("=");
}
}
return to.toString();
}
}
前端调用接口
HTML
//这里只是为了测试数据 页面有点low
<html>
<head>
<title>dsfsaf</title>
</head>
<body>
<form action="https://localhost/getCardMessage" method="post" enctype=multipart/form-data>
<input type="text" name="file" /> //这里输入我们的身份证图片地址
<input type="text" name="direction" value="front" hidden/>//照片面传入front 国徽面传入back
<button type="submit">上传</button>
</form>
</body>
</html>
页面调用返回的结果 这里只是照片面的数据
国徽面返回的结果
{“words_result”:{“失效日期”:{“words”:“20271106”,“location”:{“top”:394,“left”:100,“width”:24,“height”:104}},“签发机关”:{“words”:“辽阳市*局白塔*”,“location”:{“top”:282,“left”:144,“width”:27,“height”:200}},“签发日期”:{“words”:“20171106”,“location”:{“top”:282,“left”:98,“width”:24,“height”:100}}},“log_id”:1349655879124779008,“risk_type”:“normal”,“words_result_num”:3,“image_status”:“reversed_side”}
本文地址:https://blog.csdn.net/weixin_51591918/article/details/112621245
下一篇: MyBatis foreach 批量更新