这次 给大家带来的是百度的身份证图片识别,总体来是属于比较简单的,百度的API开发文档也写的比较清楚:https://ai.baidu.com/docs#/OCR-API-Idcard/41062b1a
使用百度身份证识别前要先申请百度的账号以及申请相对应用 https://cloud.baidu.com/
选择 产品-->人工智能-->文字识别-->卡证文字识别 进到里面选择身份证识别
再选择管理应用 点击身份证识别添加应用
得到等会需要用到的API Key 和 Secret Key
准备工作已经完成了 现在直接上代码,因为比较简单,我就不一一解释,不懂的就留言好了
pom.xml
<!--百度文字识别接口--><dependency><groupId>com.baidu.aip</groupId><artifactId>java-sdk</artifactId><version>4.3.2</version></dependency>
import org.springframework.boot.configurationprocessor.json.JSONObject;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;public class BaiDuOCR {public static String getAuth() {// 官网获取的 API KeyString clientId = "GZaw2gGRPWV4**********";// 官网获取的 Secret KeyString clientSecret = "sBOEHzGShfGC*************";return getAuth(clientId, clientSecret);}/*** 获取token* @param ak* @param sk* @return*/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();//百度推荐使用POST请求connection.setRequestMethod("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.out.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;}/*** 调用OCR* @param httpUrl* @param httpArg* @return*/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方法:POSTconnection.setRequestMethod("POST");//设置其Header的Content-Type参数为application/x-www-form-urlencodedconnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");// 填入apikey到HTTP headerconnection.setRequestProperty("apikey", "uml8HFzu2hFd8iEG2LkQGMxm");//将第二步获取到的token填入到HTTP headerconnection.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;}/***身份证参数转换* @param jsonResult* @return*/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("姓名", value);break;case "民族":map.put("民族", value);break;case "住址":map.put("住址", value);break;case "公民身份号码":map.put("公民身份号码", value);break;case "出生":map.put("出生日期", value);break;case "性别":map.put("性别", value);break;case "失效日期":map.put("失效日期", value);break;case "签发日期":map.put("签发日期", value);break;case "签发机关":map.put("签发机关", value);break;}}} catch (Exception e) {e.printStackTrace();}return map;}}
base64 本地文件转换
import sun.misc.BASE64Encoder;import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;public class BASE64 {/*** 将本地图片进行Base64位编码* <p>* 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();// 返回Base64编码过的字节数组字符串return encoder.encode(data);}
}
接下来 先写一个本地图片识别测试
public static void main(String[] args) {//获取本地的绝对路径图片File file = new File("F:\\timg2.jpg");//进行BASE64位编码String imageBase = BASE64.encodeImgageToBase64(file);imageBase = imageBase.replaceAll("\r\n", "");imageBase = imageBase.replaceAll("\\+", "%2B");//百度云的文字识别接口,后面参数为获取到的tokenString httpUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token="+BaiDuOCR.getAuth();//id_card_side=front 识别正面 id_card_side=back 识别背面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);for (String key : map.keySet()) {System.out.println(key +": "+ map.get(key));}}
然后再给一个是前端 传过来的时进行识别,其实和本地识别区别在于 base64的转换一样,其他都是一样的,所以顺便也给你们贴出来
/*** 图片识别* @param picOcr* @throws Exception*/@PostMapping("/ocr")public void picOCR(@RequestParam("pic") MultipartFile picOcr) throws Exception {byte[] data = null;BASE64Encoder base64Encoder = new BASE64Encoder();String base64 = base64Encoder.encode(picOcr.getBytes());base64 = base64.replaceAll("\r\n", "");base64 = base64.replaceAll("\\+", "%2B");String httpUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + BaiDuOCR.getAuth();//正面照String httpFront = "detect_direction=true&id_card_side=front&image=" + base64;//背面照String httpBack = "detect_direction=true&id_card_side=back&image=" + base64;String jsonResult = BaiDuOCR.request(httpUrl, httpFront);HashMap<String, String> map = BaiDuOCR.getHashMapByJson(jsonResult);for (String key : map.keySet()) {System.out.println(key + ": " + map.get(key));}}
正面识别结果:
背面识别结果:
百度身份证图片识别完成~~~~~