通过调用百度的接口,实现身份证银行卡的信息识别
前提:需要在百度创建账号,创建应用,获取AppID,API Key,Secret Key。
百度文档链接:https://cloud.baidu.com/doc/OCR/s/rk3h7xzck
获取身份证信息与银行卡的信息类似,此处以身份证信息为例:
controller:
/** * 解析身份证信息 * @param id_card_side * @param access_token * @param image * @param response * @return */ @RequestMapping("/idcard") @ResponseBody public AjaxResult idcard(String id_card_side, String access_token, @RequestParam("image")MultipartFile image, HttpServletResponse response) { CrossComain(response); // 请求url String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard"; try { byte[] imgData = image.getBytes(); String imgStr = Base64Util.encode(imgData); String imgParam = URLEncoder.encode(imgStr, "UTF-8"); String param = "id_card_side=" + "front" + "&image=" + imgParam; String result = HttpUtil.post(url, access_token, param); System.out.println(result); Map<String,Object> ma = new HashMap<>(); JSONObject ja = JSONObject.parseObject(result); System.out.println(ja); String words_result = ja.getString("words_result"); if(words_result==null||words_result.equals("null")){ return AjaxResult.error("解析失败!"); } JSONObject jb = JSONObject.parseObject(words_result); ma.put("vAddress",JSONObject.parseObject(jb.getString("住址")).getString("words")); ma.put("vBirth",JSONObject.parseObject(jb.getString("出生")).getString("words")); ma.put("vName",JSONObject.parseObject(jb.getString("姓名")).getString("words")); ma.put("vCard",JSONObject.parseObject(jb.getString("公民身份号码")).getString("words")); if(JSONObject.parseObject(jb.getString("性别")).getString("words").equals("男")){ ma.put("vSex",1); }else{ ma.put("vSex",2); } ma.put("vNation",JSONObject.parseObject(jb.getString("民族")).getString("words")); return AjaxResult.success("解析成功!",ma); } catch (Exception e) { e.printStackTrace(); } return null; }
base64工具类:
/** * 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(); }
http工具类
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; }
html:body
<div class="headTitle fixationHead"> <div class="name">户主信息</div> <div class="addBtn" @click="addIdCardClick">拍照/上传身份证</div> <input type="file" id="idcard" style="display: none;" @change="addIdCardChange()" accept="image/*"> </div>
html :function
addIdCardClick:function(){ // 弹出文件选择框 let input = document.getElementById('idcard'); input.click(); }, addIdCardChange:function(){ var _this =this; _this.loadingDiv = true; $.ajax({ async:true,//同步,异步 url:router.server+"/project/operate/AccessToken", //请求的服务端地址 type:"post", success:function(data){ debugger var formData=new FormData(); let resultFile = document.getElementById('idcard').files[0]; formData.append("access_token",data); formData.append("id_card_side","front"); formData.append("image",resultFile); $.ajax({ type: "post", url: router.server+"/project/operate/idcard", async: true, data: formData, dataType: "json", cache: false, processData: false, contentType: false, success: function (data) { _this.formData.vAddress = data.data.vAddress; _this.formData.vBirth = data.data.vBirth; _this.formData.vName = data.data.vName; _this.formData.vCard = data.data.vCard; _this.formData.vSex = data.data.vSex; _this.formData.vNation = data.data.vNation; // 页面初始化完成 加载遮罩隐藏 _this.loadingDiv = false; }, error: function (xhr) { console.log("请求解析失败"); } }); }, error:function(){ alert('error'); //错误的处理 _this.loadingDiv = false; } });
总结:此处采用的方式是通过formData传参,后天获取文件流,直接解析,返回数据到前台。