第一步:准备工作

我们这里调用的是百度的身份证识别api,我们可以在百度的api里申请这个api权限每天有500次调用机会
网站申请地址:https://ai.baidu.com/ 需要用到我们的API Key Secret Key 请保存好

第二部:Java后端编写代码并解析数据

@RequestMapping(value = "getCardMessage",method = RequestMethod.POST)@ResponseBodypublic String baiDuCard(@RequestBody String file){String auth = BaiDuCardIdentification.getAuth("API Key","Secret Key");//获取access_tokenJSONObject 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) {// 请求urlString 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的Bufferbyte[] 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”}

java实现身份证识别相关推荐

  1. Java实现身份证识别注册

    博主在开发项目时,需要使用Java完成身份证识别功能,如图所示: 后来,便采取了百度识别接口中的身份证识别技术,即通过该接口,实现识别身份证中的信息.下面是实现步骤: 首先,需要去百度平台开通百度身份 ...

  2. java百度身份证识别

    在项目里因客户要求在注册时要求上传身份证照片来识别身份证上信息来录入信息资料,于是采用了百度OCR文字识别,废话不多说,进入正题 1.登录百度云(没有就先注册) 在全部产品 - 人工智能 - 文字识别 ...

  3. 服务器身份证识别银行卡识别系统

    服务器身份证识别银行卡识别系统的网络结构 由Web Service和其相关网站接收客户端上传的需要识别的证件图片,客户端可以是PC的客户端程序,可以是PC的浏览器.手机或其他便携式设备.当Web Se ...

  4. 利用Java进行身份证正反面信息识别

    利用Java进行身份证正反面信息识别 1.百度授权信息准备 首先你得在百度AI开放平台上面注册一个账号,或者已经有百度账号了,网址是:https://ai.baidu.com/,如下图所示: 然后点击 ...

  5. java实现身份证正反面图片的身份信息的识别

    身份正图片的识别及身份信息的读取,在软件开发中时有用到:本文详细介绍身份证图片的识别,能够判定照片是否为身份证照片并提示照片是否为临时身份证.身份证复印件等风险信息,能够判定照片是否为图片处理软件编辑 ...

  6. Java实现阿里云OCR的身份证识别等功能具体流程(包括android思路)

    项目中需要使用到身份证识别,所以经过调研后决定从阿里云上购买,在经过我的两天研究和客服对接,我基本把坑全踩完了,所以在此总结一套整体的流程 首先,在我买过之后才发现,阿里云的官网上面有两套ocr,第一 ...

  7. java 跟据身份证识别性别年龄

    java 跟据身份证识别性别年龄 package com.bdzk.sys.config.utils;import java.text.SimpleDateFormat; import java.ut ...

  8. 关于调用百度云OCR身份证识别接口,用Java语言,识别结果缺少身份证号码的问题解决

    问题描述: 最近项目系统开发,使用到了相关证件的信息提取.识别,由于是学校科研使用,选择了百度云OCR文字识别的API.具体的相关识别身份等证件的代码将在另一篇文章中叙述,最近真的太忙了,草稿箱中还有 ...

  9. java实现人脸识别(使用百度云V3版本)

    2017年,开发了第一个版本的人脸识别,当时费时有5天之久终于写出来了,但是只适用于火狐浏览器,别的浏览器都打不开摄像头. 2018年,将人脸识别重新完善,可以支持360.火狐.谷歌等主流浏览器,版本 ...

  10. 扫一扫 移动端_移动端手机APP 身份证识别 手机扫一扫离线识别

    证件识别是指能实现拍照自动输入身份信息,让用户完全告别手动输入身份证.驾驶证.行驶证等证件信息.它支持Android. iOS .Java.Linux等多终端形式接入,电 一山一,领九九,六八九八菱还 ...

最新文章

  1. 使用PowerShell收集客户端MAC地址
  2. mongodb简单的函数
  3. cd1101d 树形dp
  4. [Python] NotImplemented 和 NotImplementedError 区别
  5. mysql时间字段不走索引_MySQL使用=或=范围查询时不走索引
  6. 深度优先,广度优先,拓扑排序(实战题解)
  7. 黑客已经盗了 $15,945,221.72 美元!
  8. 基于40万表格数据集TableBank,用MaskRCNN做表格检测
  9. 我眼中的解决方案架构师
  10. 在html中滚动条显示的属性,html滚动条textarea属性设置本 textarea怎么显示滚动条...
  11. 几楼电路精灵——手机端 原理图 PCB
  12. 同比与环比——财务小知识点
  13. uni-app(H5)拼图游戏
  14. NBA表格_数据分析NBA历史前十球星排名
  15. Ajax提交与submit提交对比
  16. 他是阿里P11,靠写代码写成合伙人,身家几十亿,没有他,我们可能刷不了淘宝!...
  17. 如何禁用笔记本电脑触摸板_您如何永久禁用笔记本电脑上的触摸板?
  18. UCI 机器学习数据集(分类)
  19. python同步远程文件夹_python pyinotify 监控远程文件夹来实现即时全量同步
  20. 谭浩强c语言课后习题笔记[1-4章]

热门文章

  1. python破解wifi-Python利用字典破解WIFI密码的方法
  2. Java打印菱形(一)
  3. python基础语法篇——输入与输出
  4. Python 音频: sounddevice 使用 左声道/右声道/立体声 --- 播放,录音
  5. 计算机及编程语言历史概述
  6. xenCenter创建镜像库和挂载硬盘
  7. 用python偷懒Arcgis(地类编码转地类名称)
  8. JavaScript如何调用摄像头
  9. STM32电机库(ST-MC-Workbench)学习记录——电机参数及传感器设置
  10. JDK API 1.60 中文版(Java 1.6 中文帮助文档) 中文版