java通过百度AI开发平台提取身份证图片中的文字信息
废话不多说,直接上代码。。。
IdCardDemo.java
- package com.wulss.baidubce;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.util.Map;
- import com.wulss.utils.Base64Util;
- import com.wulss.utils.FileUtil;
- import com.wulss.utils.HttpUtil;
- /**
- *
- * @Descript TODO (身份证图片识别 案例)
- * @author yeting
- * @date 2019年4月18日
- *
- */
- public class IdCardDemo {
- private static final String URL_IDCARD = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";//身份证识别地址
- private static final String URL_ACCESSTOKEN = "https://aip.baidubce.com/oauth/2.0/token?"; // 百度AI开发平台 获取token的地址
- private static final String API_KEY = "afdH343CAt342YFT7F"; // 百度AI开发平台 获取的 API Key 更新为你注册的
- private static final String SECRET_KEY = "js45sdfqRFF65gOd667sd1R7sdr"; // 百度AI开发平台 获取的 Secret Key 更新为你注册的
- /**
- * 获取API访问token
- * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
- * @param ak - 百度云官网获取的 API Key
- * @param sk - 百度云官网获取的 Securet Key
- * @return assess_token 示例:
- * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
- */
- public static String getAccessToken() {
- String getAccessTokenUrl = URL_ACCESSTOKEN
- + "grant_type = client_credentials" // 1. grant_type为固定参数
- + "&client_id = " + API_KEY // 2. 官网获取的 API Key
- + "&client_secret = " + SECRET_KEY; // 3. 官网获取的 Secret Key
- String accessToken = "";
- try {
- URL realUrl = new URL(getAccessTokenUrl);
- // 打开和URL之间的连接
- HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
- connection.setRequestMethod("GET");
- connection.connect();
- // 获取所有响应头字段
- // 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;
- }
- System.err.println("result:" + result);
- org.json.JSONObject jsonObject = new org.json.JSONObject(result);
- accessToken = jsonObject.getString("access_token");
- } catch (Exception e) {
- System.err.printf("获取token失败!");
- e.printStackTrace(System.err);
- }
- return accessToken;
- }
- /**
- * 身份证识别请求
- * @param side 识别身份证正面 front;识别身份证背面 back;
- * @param filePath 图片路径
- * @param accessToken 线上环境有过期时间, 客户端可自行缓存,过期后重新获取。
- * @return 返回身份证号码
- */
- public static String requestIdCard(String side,String filePath,String accessToken) {
- String result = "";
- try {
- //1.请求获取结果
- String requestParams = "id_card_side = " + side
- + "&" + URLEncoder.encode("image", "UTF-8")
- + "=" + URLEncoder.encode(Base64Util.encode(FileUtil.readFileByBytes(filePath)), "UTF-8");
- result = HttpUtil.post(URL_IDCARD, accessToken, requestParams);//返回json格式的结果
- System.out.println(result);
- // 请求返回结果eg:
- // String result =
- // "[{\"log_id\": 3812339812321238679, \"words_result_num\": 6,\"direction\": 2, \"image_status\": \"normal\",
- // \"words_result\": {
- // \"住址\":{\"location\": {\"width\": 123, \"top\": 123, \"height\": 4423, \"left\":1232}, \"words\": \"湖北省咸宁市茶叶巷\"},
- // \"出生\": {\"location\":{\"width\": 333, \"top\": 339, \"height\": 2333, \"left\": 3333}, \"words\": \"19191010\"},
- // \"姓名\": {\"location\": {\"width\": 133, \"top\": 309, \"height\": 303, \"left\": 2205}, \"words\": \"张三\"},
- // \"公民身份号码\":{\"location\": {\"width\": 111, \"top\": 3333, \"height\": 3335, \"left\":333}, \"words\": \"430124191910101234\"},
- // \"性别\": {\"location\": {\"width\":222, \"top\": 521, \"height\": 304, \"left\": 2333}, \"words\": \"男\"},
- // \"民族\": {\"location\": {\"width\": 111, \"top\": 3333, \"height\": 22,\"left\": 1222}, \"words\": \"汉\"}
- // }
- // }]";
- // <!-- json转换工具 依赖jar包-->
- // <dependency>
- // <groupId>net.sf.json-lib</groupId>
- // <artifactId>json-lib</artifactId>
- // <version>2.4</version>
- // <classifier>jdk15</classifier>
- // </dependency>
- //2.解析结果
- Map<String,String> resultMap = (Map<String,String>)net.sf.json.JSONObject
- .toBean(net.sf.json.JSONObject.fromObject(result),Map.class);
- if(resultMap.get("error_code").equals("110")) {
- return requestIdCard(side,filePath,getAccessToken()) ;//重新请求
- }else {
- String words = "";
- if(resultMap.get("image_status") != null && resultMap.get("image_status").equals("normal")) {// 正常
- String wordsResults = resultMap.get("words_result");
- Map<String,String> wordsResultMap = (Map<String,String>)net.sf.json.JSONObject
- .toBean(net.sf.json.JSONObject.fromObject(wordsResults),Map.class);
- String idCardNums = wordsResultMap.get("公民身份号码");
- Map<String,String> idCardNumMap = (Map<String,String>)net.sf.json.JSONObject
- .toBean(net.sf.json.JSONObject.fromObject(idCardNums),Map.class);
- words = idCardNumMap.get("words");
- }
- return words;
- }
- } catch (Exception e) {
- e.printStackTrace();
- result = e.getMessage();
- }
- return result;
- }
- }
FileUtil.java
- package com.wulss.utils;
- 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();
- }
- }
- }
- }
Base64Util.java
- package com.wulss.utils;
- /**
- * Base64 工具类
- */
- public class Base64Util {
- private static final char[] ALPHABET;
- private static final char last2byte;
- private static final char last4byte;
- private static final char last6byte;
- private static final char lead6byte;
- private static final char lead4byte;
- private static final char lead2byte;
- private static final char[] encodeTable;
- private static int[] toInt;
- static {
- ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
- last2byte = (char)Integer.parseInt("00000011", 2);
- last4byte = (char)Integer.parseInt("00001111", 2);
- last6byte = (char)Integer.parseInt("00111111", 2);
- lead6byte = (char)Integer.parseInt("11111100", 2);
- lead4byte = (char)Integer.parseInt("11110000", 2);
- lead2byte = (char)Integer.parseInt("11000000", 2);
- 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', '+', '/' };
- Base64Util.toInt = new int[128];
- for (int i = 0; i < Base64Util.ALPHABET.length; ++i) {
- Base64Util.toInt[Base64Util.ALPHABET[i]] = i;
- }
- }
- 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();
- }
- public static byte[] decode(final String s) {
- final int delta = s.endsWith("==") ? 2 : (s.endsWith("=") ? 1 : 0);
- final byte[] buffer = new byte[s.length() * 3 / 4 - delta];
- final int mask = 255;
- int index = 0;
- for (int i = 0; i < s.length(); i += 4) {
- final int c0 = Base64Util.toInt[s.charAt(i)];
- final int c2 = Base64Util.toInt[s.charAt(i + 1)];
- buffer[index++] = (byte)((c0 << 2 | c2 >> 4) & mask);
- if (index >= buffer.length) {
- return buffer;
- }
- final int c3 = Base64Util.toInt[s.charAt(i + 2)];
- buffer[index++] = (byte)((c2 << 4 | c3 >> 2) & mask);
- if (index >= buffer.length) {
- return buffer;
- }
- final int c4 = Base64Util.toInt[s.charAt(i + 3)];
- buffer[index++] = (byte)((c3 << 6 | c4) & mask);
- }
- return buffer;
- }
- }
HttpUtil.java
- package com.wulss.utils;
- 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;
- }
- }
java通过百度AI开发平台提取身份证图片中的文字信息的更多相关文章
- 百度AI开发平台简介
AIstudio https://aistudio.baidu.com/aistudio/index 关于AI Studio AI Studio是基于百度深度学习平台飞桨的一站式AI开发平台,提供在线 ...
- 基于百度AI开放平台的人脸识别及语音合成
基于百度AI的人脸识别及语音合成课题 课题需求 (1)人脸识别 在Web界面上传人的照片,后台使用Java技术接收图片,然后对图片进行解码,调用云平台接口识别人脸特征,接收平台返回的人员年龄.性别.颜 ...
- 百度AI开放平台- API实战调用
百度AI开放平台- API实战调用 一. 前言 首先说一下项目需求. 两个用户,分别上传了两段不同的文字,要计算两段文字相似度有多少,匹配数据库中的符合条件的数据,初步估计列出来会有60-1 ...
- python基于百度AI开发文字识别
很多场景都会用到文字识别,比如app或者网站里都会上传身份证等证件以及财务系统识别报销证件等等 第一步,你需要去百度AI里去注册一个账号,然后新建一个文字识别的应用 然后你将得到一个API Key 和 ...
- 调用百度地图开发平台的JavascriptAPI实现将市县位置转换成坐标
最近的项目要做的地图比较多,有的还比较复杂,而地图用到的坐标,上网找json文件更是良莠不齐的.真是让人伤脑筋,后来突然想到了百度地图开发平台,没想到真的有对应的API哦,谢天谢地!!!下面说一下完整 ...
- jQuery:[2]百度地图开发平台实战
jQuery:[2]百度地图开发平台实战 原文链接: http://blog.csdn.net/moniteryao/article/details/51078779 快速开始 开发平台地址 ht ...
- 百度AI开放平台,语音识别,语音合成以及短文本相似度
百度AI开放平台:https://ai.baidu.com/ 语音合成 from aip import AipSpeech APP_ID=" #'你的 App ID' API_KEY=&qu ...
- selenium自动化 | 借助百度AI开放平台识别验证码登录职教云
#通过借助百度AI开放平台识别验证码登录职教云 from PIL import Image from aip import AipOcr import unittest # driver.get(zj ...
- 百度AI开放平台 UNIT平台开发在线客服 借助百度的人工智能如何开发一个在线客服系统
这段时间在研究一些人工智能的产品,对比了国内几家做人工智能在线客服的,有些接口是要收费的,有些是免费的,但是做了很多限制,比如每天调用的接口次数限制是100次.后来就找到了百度的AI,大家也知道,目前 ...
随机推荐
- JS中sort()方法的用法,参数以及排序原理
sort() 方法用于对数组的元素进行排序,并返回数组.默认排序顺序是根据字符串Unicode码点.语法:arrayObject.sort(sortby):参数sortby可选.规定排序顺序.必须是函 ...
- .net core 下编码问题
System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("zh-CN&q ...
- css文本超出隐藏显示省略号
p style="width: 300px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;"> 如 ...
- matlab练习程序(波纹扭曲)
其实就是用sin或cos对x,y坐标进行变换,处理的时候依然是反向变换. 类似的,用不同的函数能得到不同的扭曲效果,比如log,1/x,exp等等. 效果如下: 代码如下(还给出了如何生成gif图片的 ...
- [Python][小知识][NO.4] wxPython 字体选择对话框(O.O 不知道放到那里就放到这个分类的)
1.前言 O.O 前两天回家浪了两天,断更了 哎~~~ o.o 有时候,有木有想改标签或编辑框中内容的字体呀?(o.o 反正我是没有). wxpython也可以说是所在的操作系统,有字体选择器,给我们 ...
- 2019年Web前端入门的自学路线
本文最初发表于博客园,并在GitHub上持续更新前端的系列文章.欢迎在GitHub上关注我,一起入门和进阶前端. 以下是正文.本文内容不定期更新. 我前几天写过一篇文章:<裸辞两个月,海投一个月 ...
- Spark性能优化【OOM】
一.异常情况 Spark on yarn模式下,当yarn为client的模式时没有OOM而cluster模式下出现OOM 二.异常分析 由于client模型没有出现OOM而cluster模式出现OO ...
- Redis常用命令【字符串】
1.启动Redis客户端 进入src目录下,执行:redis-cli启动Redis客户端 2.help 帮助 帮助命令,用来查看redis命令的使用方式 3.set 设置 3.1设置 3.2不存在才设 ...
- Wampserver或者帝国CMS安装后, 打开localhost显示IIS欢迎界面图片
我们在安装集成环境Wampserver或者帝国CMS之后,有时会遇到一个问题, 打开localhost显示一张IIS欢迎界面图片,这个问题该如何解决呢,我在这里简单整理了一下解决方法 电脑win10系 ...
- (转)Debian 安装与卸载包命令
1.APT主要命令apt-cache search ------package 搜索包sudo apt-get install ------package 安装包sudo apt-get remov ...