废话不多说,直接上代码。。。

  IdCardDemo.java

  1. package com.wulss.baidubce;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.InputStreamReader;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.net.URLEncoder;
  8. import java.util.Map;
  9.  
  10. import com.wulss.utils.Base64Util;
  11. import com.wulss.utils.FileUtil;
  12. import com.wulss.utils.HttpUtil;
  13.  
  14. /**
  15. *
  16. * @Descript TODO (身份证图片识别 案例)
  17. * @author yeting
  18. * @date 2019年4月18日
  19. *
  20. */
  21. public class IdCardDemo {
  22.  
  23. private static final String URL_IDCARD = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";//身份证识别地址
  24. private static final String URL_ACCESSTOKEN = "https://aip.baidubce.com/oauth/2.0/token?"; // 百度AI开发平台 获取token的地址
  25. private static final String API_KEY = "afdH343CAt342YFT7F"; // 百度AI开发平台 获取的 API Key 更新为你注册的
  26. private static final String SECRET_KEY = "js45sdfqRFF65gOd667sd1R7sdr"; // 百度AI开发平台 获取的 Secret Key 更新为你注册的
  27.  
  28. /**
  29. * 获取API访问token
  30. * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
  31. * @param ak - 百度云官网获取的 API Key
  32. * @param sk - 百度云官网获取的 Securet Key
  33. * @return assess_token 示例:
  34. * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
  35. */
  36. public static String getAccessToken() {
  37. String getAccessTokenUrl = URL_ACCESSTOKEN
  38. + "grant_type = client_credentials" // 1. grant_type为固定参数
  39. + "&client_id = " + API_KEY // 2. 官网获取的 API Key
  40. + "&client_secret = " + SECRET_KEY; // 3. 官网获取的 Secret Key
  41. String accessToken = "";
  42. try {
  43. URL realUrl = new URL(getAccessTokenUrl);
  44.  
  45. // 打开和URL之间的连接
  46. HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
  47. connection.setRequestMethod("GET");
  48. connection.connect();
  49.  
  50. // 获取所有响应头字段
  51. // Map<String, List<String>> map = connection.getHeaderFields();
  52. // 遍历所有的响应头字段
  53. // for (String key : map.keySet()) {
  54. // System.err.println(key + "--->" + map.get(key));
  55. // }
  56.  
  57. // 定义 BufferedReader输入流来读取URL的响应
  58. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  59. String result = "";
  60. String line;
  61. while ((line = in.readLine()) != null) {
  62. result += line;
  63. }
  64.  
  65. System.err.println("result:" + result);
  66.  
  67. org.json.JSONObject jsonObject = new org.json.JSONObject(result);
  68. accessToken = jsonObject.getString("access_token");
  69. } catch (Exception e) {
  70. System.err.printf("获取token失败!");
  71. e.printStackTrace(System.err);
  72. }
  73. return accessToken;
  74. }
  75.  
  76. /**
  77. * 身份证识别请求
  78. * @param side 识别身份证正面 front;识别身份证背面 back;
  79. * @param filePath 图片路径
  80. * @param accessToken 线上环境有过期时间, 客户端可自行缓存,过期后重新获取。
  81. * @return 返回身份证号码
  82. */
  83. public static String requestIdCard(String side,String filePath,String accessToken) {
  84. String result = "";
  85.  
  86. try {
  87. //1.请求获取结果
  88. String requestParams = "id_card_side = " + side
  89. + "&" + URLEncoder.encode("image", "UTF-8")
  90. + "=" + URLEncoder.encode(Base64Util.encode(FileUtil.readFileByBytes(filePath)), "UTF-8");
  91.  
  92. result = HttpUtil.post(URL_IDCARD, accessToken, requestParams);//返回json格式的结果
  93. System.out.println(result);
  94.  
  95. // 请求返回结果eg:
  96. // String result =
  97. // "[{\"log_id\": 3812339812321238679, \"words_result_num\": 6,\"direction\": 2, \"image_status\": \"normal\",
  98. // \"words_result\": {
  99. // \"住址\":{\"location\": {\"width\": 123, \"top\": 123, \"height\": 4423, \"left\":1232}, \"words\": \"湖北省咸宁市茶叶巷\"},
  100. // \"出生\": {\"location\":{\"width\": 333, \"top\": 339, \"height\": 2333, \"left\": 3333}, \"words\": \"19191010\"},
  101. // \"姓名\": {\"location\": {\"width\": 133, \"top\": 309, \"height\": 303, \"left\": 2205}, \"words\": \"张三\"},
  102. // \"公民身份号码\":{\"location\": {\"width\": 111, \"top\": 3333, \"height\": 3335, \"left\":333}, \"words\": \"430124191910101234\"},
  103. // \"性别\": {\"location\": {\"width\":222, \"top\": 521, \"height\": 304, \"left\": 2333}, \"words\": \"男\"},
  104. // \"民族\": {\"location\": {\"width\": 111, \"top\": 3333, \"height\": 22,\"left\": 1222}, \"words\": \"汉\"}
  105. // }
  106. // }]";
  107.  
  108. // <!-- json转换工具 依赖jar包-->
  109. // <dependency>
  110. // <groupId>net.sf.json-lib</groupId>
  111. // <artifactId>json-lib</artifactId>
  112. // <version>2.4</version>
  113. // <classifier>jdk15</classifier>
  114. // </dependency>
  115.  
  116. //2.解析结果
  117. Map<String,String> resultMap = (Map<String,String>)net.sf.json.JSONObject
  118. .toBean(net.sf.json.JSONObject.fromObject(result),Map.class);
  119.  
  120. if(resultMap.get("error_code").equals("110")) {
  121. return requestIdCard(side,filePath,getAccessToken()) ;//重新请求
  122. }else {
  123. String words = "";
  124. if(resultMap.get("image_status") != null && resultMap.get("image_status").equals("normal")) {// 正常
  125. String wordsResults = resultMap.get("words_result");
  126. Map<String,String> wordsResultMap = (Map<String,String>)net.sf.json.JSONObject
  127. .toBean(net.sf.json.JSONObject.fromObject(wordsResults),Map.class);
  128.  
  129. String idCardNums = wordsResultMap.get("公民身份号码");
  130. Map<String,String> idCardNumMap = (Map<String,String>)net.sf.json.JSONObject
  131. .toBean(net.sf.json.JSONObject.fromObject(idCardNums),Map.class);
  132. words = idCardNumMap.get("words");
  133. }
  134. return words;
  135. }
  136. } catch (Exception e) {
  137. e.printStackTrace();
  138. result = e.getMessage();
  139. }
  140.  
  141. return result;
  142. }
  143.  
  144. }

  FileUtil.java

  1. package com.wulss.utils;
  2. import java.io.*;
  3.  
  4. /**
  5. * 文件读取工具类
  6. */
  7. public class FileUtil {
  8.  
  9. /**
  10. * 读取文件内容,作为字符串返回
  11. */
  12. public static String readFileAsString(String filePath) throws IOException {
  13. File file = new File(filePath);
  14. if (!file.exists()) {
  15. throw new FileNotFoundException(filePath);
  16. }
  17.  
  18. if (file.length() > 1024 * 1024 * 1024) {
  19. throw new IOException("File is too large");
  20. }
  21.  
  22. StringBuilder sb = new StringBuilder((int) (file.length()));
  23. // 创建字节输入流
  24. FileInputStream fis = new FileInputStream(filePath);
  25. // 创建一个长度为10240的Buffer
  26. byte[] bbuf = new byte[10240];
  27. // 用于保存实际读取的字节数
  28. int hasRead = 0;
  29. while ( (hasRead = fis.read(bbuf)) > 0 ) {
  30. sb.append(new String(bbuf, 0, hasRead));
  31. }
  32. fis.close();
  33. return sb.toString();
  34. }
  35.  
  36. /**
  37. * 根据文件路径读取byte[] 数组
  38. */
  39. public static byte[] readFileByBytes(String filePath) throws IOException {
  40. File file = new File(filePath);
  41. if (!file.exists()) {
  42. throw new FileNotFoundException(filePath);
  43. } else {
  44. ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
  45. BufferedInputStream in = null;
  46.  
  47. try {
  48. in = new BufferedInputStream(new FileInputStream(file));
  49. short bufSize = 1024;
  50. byte[] buffer = new byte[bufSize];
  51. int len1;
  52. while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
  53. bos.write(buffer, 0, len1);
  54. }
  55.  
  56. byte[] var7 = bos.toByteArray();
  57. return var7;
  58. } finally {
  59. try {
  60. if (in != null) {
  61. in.close();
  62. }
  63. } catch (IOException var14) {
  64. var14.printStackTrace();
  65. }
  66.  
  67. bos.close();
  68. }
  69. }
  70. }
  71. }

  Base64Util.java

  1. package com.wulss.utils;
  2.  
  3. /**
  4. * Base64 工具类
  5. */
  6. public class Base64Util {
  7. private static final char[] ALPHABET;
  8. private static final char last2byte;
  9. private static final char last4byte;
  10. private static final char last6byte;
  11. private static final char lead6byte;
  12. private static final char lead4byte;
  13. private static final char lead2byte;
  14. private static final char[] encodeTable;
  15. private static int[] toInt;
  16.  
  17. static {
  18. ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
  19. last2byte = (char)Integer.parseInt("00000011", 2);
  20. last4byte = (char)Integer.parseInt("00001111", 2);
  21. last6byte = (char)Integer.parseInt("00111111", 2);
  22. lead6byte = (char)Integer.parseInt("11111100", 2);
  23. lead4byte = (char)Integer.parseInt("11110000", 2);
  24. lead2byte = (char)Integer.parseInt("11000000", 2);
  25. 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', '+', '/' };
  26. Base64Util.toInt = new int[128];
  27. for (int i = 0; i < Base64Util.ALPHABET.length; ++i) {
  28. Base64Util.toInt[Base64Util.ALPHABET[i]] = i;
  29. }
  30. }
  31. public Base64Util() {
  32. }
  33.  
  34. public static String encode(byte[] from) {
  35. StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
  36. int num = 0;
  37. char currentByte = 0;
  38.  
  39. int i;
  40. for (i = 0; i < from.length; ++i) {
  41. for (num %= 8; num < 8; num += 6) {
  42. switch (num) {
  43. case 0:
  44. currentByte = (char) (from[i] & lead6byte);
  45. currentByte = (char) (currentByte >>> 2);
  46. case 1:
  47. case 3:
  48. case 5:
  49. default:
  50. break;
  51. case 2:
  52. currentByte = (char) (from[i] & last6byte);
  53. break;
  54. case 4:
  55. currentByte = (char) (from[i] & last4byte);
  56. currentByte = (char) (currentByte << 2);
  57. if (i + 1 < from.length) {
  58. currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
  59. }
  60. break;
  61. case 6:
  62. currentByte = (char) (from[i] & last2byte);
  63. currentByte = (char) (currentByte << 4);
  64. if (i + 1 < from.length) {
  65. currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
  66. }
  67. }
  68.  
  69. to.append(encodeTable[currentByte]);
  70. }
  71. }
  72.  
  73. if (to.length() % 4 != 0) {
  74. for (i = 4 - to.length() % 4; i > 0; --i) {
  75. to.append("=");
  76. }
  77. }
  78.  
  79. return to.toString();
  80. }
  81.  
  82. public static byte[] decode(final String s) {
  83. final int delta = s.endsWith("==") ? 2 : (s.endsWith("=") ? 1 : 0);
  84. final byte[] buffer = new byte[s.length() * 3 / 4 - delta];
  85. final int mask = 255;
  86. int index = 0;
  87. for (int i = 0; i < s.length(); i += 4) {
  88. final int c0 = Base64Util.toInt[s.charAt(i)];
  89. final int c2 = Base64Util.toInt[s.charAt(i + 1)];
  90. buffer[index++] = (byte)((c0 << 2 | c2 >> 4) & mask);
  91. if (index >= buffer.length) {
  92. return buffer;
  93. }
  94. final int c3 = Base64Util.toInt[s.charAt(i + 2)];
  95. buffer[index++] = (byte)((c2 << 4 | c3 >> 2) & mask);
  96. if (index >= buffer.length) {
  97. return buffer;
  98. }
  99. final int c4 = Base64Util.toInt[s.charAt(i + 3)];
  100. buffer[index++] = (byte)((c3 << 6 | c4) & mask);
  101. }
  102. return buffer;
  103. }
  104. }

  HttpUtil.java

  1. package com.wulss.utils;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.DataOutputStream;
  5. import java.io.InputStreamReader;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.util.List;
  9. import java.util.Map;
  10.  
  11. /**
  12. * http 工具类
  13. */
  14. public class HttpUtil {
  15.  
  16. public static String post(String requestUrl, String accessToken, String params)
  17. throws Exception {
  18. String contentType = "application/x-www-form-urlencoded";
  19. return HttpUtil.post(requestUrl, accessToken, contentType, params);
  20. }
  21.  
  22. public static String post(String requestUrl, String accessToken, String contentType, String params)
  23. throws Exception {
  24. String encoding = "UTF-8";
  25. if (requestUrl.contains("nlp")) {
  26. encoding = "GBK";
  27. }
  28. return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
  29. }
  30.  
  31. public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
  32. throws Exception {
  33. String url = requestUrl + "?access_token=" + accessToken;
  34. return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
  35. }
  36.  
  37. public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
  38. throws Exception {
  39. URL url = new URL(generalUrl);
  40. // 打开和URL之间的连接
  41. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  42. connection.setRequestMethod("POST");
  43. // 设置通用的请求属性
  44. connection.setRequestProperty("Content-Type", contentType);
  45. connection.setRequestProperty("Connection", "Keep-Alive");
  46. connection.setUseCaches(false);
  47. connection.setDoOutput(true);
  48. connection.setDoInput(true);
  49.  
  50. // 得到请求的输出流对象
  51. DataOutputStream out = new DataOutputStream(connection.getOutputStream());
  52. out.write(params.getBytes(encoding));
  53. out.flush();
  54. out.close();
  55.  
  56. // 建立实际的连接
  57. connection.connect();
  58. // 获取所有响应头字段
  59. Map<String, List<String>> headers = connection.getHeaderFields();
  60. // 遍历所有的响应头字段
  61. for (String key : headers.keySet()) {
  62. System.err.println(key + "--->" + headers.get(key));
  63. }
  64. // 定义 BufferedReader输入流来读取URL的响应
  65. BufferedReader in = null;
  66. in = new BufferedReader(
  67. new InputStreamReader(connection.getInputStream(), encoding));
  68. String result = "";
  69. String getLine;
  70. while ((getLine = in.readLine()) != null) {
  71. result += getLine;
  72. }
  73. in.close();
  74. System.err.println("result:" + result);
  75. return result;
  76. }
  77. }

java通过百度AI开发平台提取身份证图片中的文字信息的更多相关文章

  1. 百度AI开发平台简介

    AIstudio https://aistudio.baidu.com/aistudio/index 关于AI Studio AI Studio是基于百度深度学习平台飞桨的一站式AI开发平台,提供在线 ...

  2. 基于百度AI开放平台的人脸识别及语音合成

    基于百度AI的人脸识别及语音合成课题 课题需求 (1)人脸识别 在Web界面上传人的照片,后台使用Java技术接收图片,然后对图片进行解码,调用云平台接口识别人脸特征,接收平台返回的人员年龄.性别.颜 ...

  3. 百度AI开放平台- API实战调用

    百度AI开放平台- API实战调用 一.      前言 首先说一下项目需求. 两个用户,分别上传了两段不同的文字,要计算两段文字相似度有多少,匹配数据库中的符合条件的数据,初步估计列出来会有60-1 ...

  4. python基于百度AI开发文字识别

    很多场景都会用到文字识别,比如app或者网站里都会上传身份证等证件以及财务系统识别报销证件等等 第一步,你需要去百度AI里去注册一个账号,然后新建一个文字识别的应用 然后你将得到一个API Key 和 ...

  5. 调用百度地图开发平台的JavascriptAPI实现将市县位置转换成坐标

    最近的项目要做的地图比较多,有的还比较复杂,而地图用到的坐标,上网找json文件更是良莠不齐的.真是让人伤脑筋,后来突然想到了百度地图开发平台,没想到真的有对应的API哦,谢天谢地!!!下面说一下完整 ...

  6. jQuery:[2]百度地图开发平台实战

    jQuery:[2]百度地图开发平台实战 原文链接:   http://blog.csdn.net/moniteryao/article/details/51078779 快速开始 开发平台地址 ht ...

  7. 百度AI开放平台,语音识别,语音合成以及短文本相似度

    百度AI开放平台:https://ai.baidu.com/ 语音合成 from aip import AipSpeech APP_ID=" #'你的 App ID' API_KEY=&qu ...

  8. selenium自动化 | 借助百度AI开放平台识别验证码登录职教云

    #通过借助百度AI开放平台识别验证码登录职教云 from PIL import Image from aip import AipOcr import unittest # driver.get(zj ...

  9. 百度AI开放平台 UNIT平台开发在线客服 借助百度的人工智能如何开发一个在线客服系统

    这段时间在研究一些人工智能的产品,对比了国内几家做人工智能在线客服的,有些接口是要收费的,有些是免费的,但是做了很多限制,比如每天调用的接口次数限制是100次.后来就找到了百度的AI,大家也知道,目前 ...

随机推荐

  1. JS中sort()方法的用法,参数以及排序原理

    sort() 方法用于对数组的元素进行排序,并返回数组.默认排序顺序是根据字符串Unicode码点.语法:arrayObject.sort(sortby):参数sortby可选.规定排序顺序.必须是函 ...

  2. .net core 下编码问题

    System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("zh-CN&q ...

  3. css文本超出隐藏显示省略号

    p style="width: 300px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;"> 如 ...

  4. matlab练习程序(波纹扭曲)

    其实就是用sin或cos对x,y坐标进行变换,处理的时候依然是反向变换. 类似的,用不同的函数能得到不同的扭曲效果,比如log,1/x,exp等等. 效果如下: 代码如下(还给出了如何生成gif图片的 ...

  5. [Python][小知识][NO.4] wxPython 字体选择对话框(O.O 不知道放到那里就放到这个分类的)

    1.前言 O.O 前两天回家浪了两天,断更了 哎~~~ o.o 有时候,有木有想改标签或编辑框中内容的字体呀?(o.o 反正我是没有). wxpython也可以说是所在的操作系统,有字体选择器,给我们 ...

  6. 2019年Web前端入门的自学路线

    本文最初发表于博客园,并在GitHub上持续更新前端的系列文章.欢迎在GitHub上关注我,一起入门和进阶前端. 以下是正文.本文内容不定期更新. 我前几天写过一篇文章:<裸辞两个月,海投一个月 ...

  7. Spark性能优化【OOM】

    一.异常情况 Spark on yarn模式下,当yarn为client的模式时没有OOM而cluster模式下出现OOM 二.异常分析 由于client模型没有出现OOM而cluster模式出现OO ...

  8. Redis常用命令【字符串】

    1.启动Redis客户端 进入src目录下,执行:redis-cli启动Redis客户端 2.help 帮助 帮助命令,用来查看redis命令的使用方式 3.set 设置 3.1设置 3.2不存在才设 ...

  9. Wampserver或者帝国CMS安装后, 打开localhost显示IIS欢迎界面图片

    我们在安装集成环境Wampserver或者帝国CMS之后,有时会遇到一个问题, 打开localhost显示一张IIS欢迎界面图片,这个问题该如何解决呢,我在这里简单整理了一下解决方法 电脑win10系 ...

  10. (转)Debian 安装与卸载包命令

    1.APT主要命令apt-cache search  ------package 搜索包sudo apt-get install ------package 安装包sudo apt-get remov ...