百度云身份证识别以及获取身份证信息
程序员文章站
2022-07-12 21:00:13
...
因为需用到百度API 所以我们需要在百度里面进去注册
飞机票 百度ai https://ai.baidu.com/tech/ocr_cards
先创建应用,按步骤填写资料
创建公共后,如下,记住APIkey, 以及Secret Key 后面需要用到
开始写代码
我们需要写几个工具类
第一个转码工具
import sun.misc.BASE64Encoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class BASE64 {
/**
* 将本地图片进行Base64位编码
*
* @param imgUrl
* 图片的url路径,如e:\\123.png
* @return
*/
public static String encodeImgageToBase64(File imageFile) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
// 其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imageFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
}
第二个文件转码
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItem;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.*;
public class MultipartToFile {
/**
* MultipartFile 转 File
* @param file
* @throws Exception
*/
public static File multipartFileToFile(MultipartFile file ) throws Exception {
File toFile = null;
if(file.equals("")||file.getSize()<=0){
file = null;
return toFile;
}else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
}
return toFile;
}
public static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
第三个 连接百度API的类
```java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;
public class BaiduOcr {
/**
* 获取权限token
*
* @return 返回示例: { "access_token":
* "24.c9303e47f0729c40f2bc2be6f8f3d589.2592000.1530936208.282335-
* 1234567", "expires_in":2592000 }
*/
public static String getAuth() {
// 官网获取的 API Key
String clientId = "这里添加你创建应用时间获得的APIkey";
// 官网获取的 Secret Key
String clientSecret = "这里填写你获得的Secret Key";
return getAuth(clientId, clientSecret);
}
/**
* 获取API访问token 该token有一定的有效期,需要自行管理,当失效时需重新获取.
*
* @param ak - 百度云的 API Key
* @param sk - 百度云的 Securet Key
* @return assess_token 示例:
* "24.c9303e47f0729c40f2bc2be6f8f3d589.2592000.1530936208.282335-1234567"
*/
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("POST");// 百度推荐使用POST请求
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 定义 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);
JSONObject jsonObject = new JSONObject(result);
String access_token = jsonObject.getString("access_token");
return access_token;
} catch (Exception e) {
System.err.printf("获取token失败!");
e.printStackTrace(System.err);
}
return null;
}
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
//用java JDK自带的URL去请求
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置该请求的消息头
//设置HTTP方法:POST
connection.setRequestMethod("POST");
//设置其Header的Content-Type参数为application/x-www-form-urlencoded
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 填入apikey到HTTP header
connection.setRequestProperty("apikey", "uml8HFzu2hFd8iEG2LkQGMxm");
//将第二步获取到的token填入到HTTP header
connection.setRequestProperty("access_token", BaiduOcr.getAuth());
connection.setDoOutput(true);
connection.getOutputStream().write(httpArg.getBytes("UTF-8"));
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static HashMap<String, String> getHashMapByJson(String jsonResult) {
HashMap map = new HashMap<String, String>();
try {
JSONObject jsonObject = new JSONObject(jsonResult);
JSONObject words_result = jsonObject.getJSONObject("words_result");
Iterator<String> it = words_result.keys();
while (it.hasNext()) {
String key = it.next();
JSONObject result = words_result.getJSONObject(key);
String value = result.getString("words");
switch (key) {
case "姓名":
map.put("name", value);
break;
case "民族":
map.put("nation", value);
break;
case "住址":
map.put("address", value);
break;
case "公民身份号码":
map.put("IDCard", value);
break;
case "出生":
map.put("Birth", value);
break;
case "性别":
map.put("sex", value);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public static HashMap<String, String> getbackByJson(String jsonResult) {
HashMap map = new HashMap<String, String>();
try {
JSONObject jsonObject = new JSONObject(jsonResult);
JSONObject words_result = jsonObject.getJSONObject("words_result");
Iterator<String> it = words_result.keys();
while (it.hasNext()) {
String key = it.next();
JSONObject result = words_result.getJSONObject(key);
System.out.println(result);
String value = result.getString("words");
switch (key) {
case "签发机关":
map.put("签发机关", value);
break;
case "签发日期":
map.put("签发日期", value);
break;
case "失效日期":
map.put("失效日期", value);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
至此,我们已经都准备好了辅助类
开始写controller
身份证正面识别
```java
@RequestMapping("/test")
public void test() {
//如果是文件上传的,用这个进行文件转换
// File newFile=MultipartToFile.multipartFileToFile(file);
//进行BASE64位编码
File newFile=new File("D:\\112\\234.jpg");
String imageBase = BASE64.encodeImgageToBase64(newFile);
imageBase = imageBase.replaceAll("\r\n", "");
imageBase = imageBase.replaceAll("\\+", "%2B");
//百度云的文字识别接口,后面参数为获取到的token
String httpUrl = " https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + BaiduOcr.getAuth();
String httpArg = "detect_direction=true&id_card_side=front&image=" + imageBase;
String jsonResult = BaiduOcr.request(httpUrl, httpArg);
System.out.println("返回的结果--------->" + jsonResult);
HashMap<String, String> map = BaiduOcr.getHashMapByJson(jsonResult);
System.out.println("身份证号码" + map.get("IDCard"));
Collection<String> values = map.values();
Iterator<String> iterator2 = values.iterator();
System.out.print(iterator2);
while (iterator2.hasNext()) {
System.out.print(iterator2.next() + ", ");
}
}
身份证反面验证
@RequestMapping("/test")
public void test() {
// File newFile=MultipartToFile.multipartFileToFile(file);
//进行BASE64位编码
File newFile=new File("D:\\112\\234.jpg");
String imageBase = BASE64.encodeImgageToBase64(newFile);
imageBase = imageBase.replaceAll("\r\n", "");
imageBase = imageBase.replaceAll("\\+", "%2B");
//百度云的文字识别接口,后面参数为获取到的token
String httpUrl = " https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + BaiduOcr.getAuth();
String httpArg = "detect_direction=true&id_card_side=back&image=" + imageBase;
String jsonResult = BaiduOcr.request(httpUrl, httpArg);
System.out.println("返回的结果--------->" + jsonResult);
HashMap<String, String> map = BaiduOcr.getHashMapByJson(jsonResult);
Collection<String> values = map.values();
Iterator<String> iterator2 = values.iterator();
System.out.print(iterator2);
while (iterator2.hasNext()) {
System.out.print(iterator2.next() + ", ");
}
}
代码就结束了,调用controller 就可以了
上一篇: 异步编程