业务需求要实现身份证照片识别,还是比较简单的,百度的API开发文档也写的比较清楚:https://ai.baidu.com/ai-doc/OCR/rk3h7xzck
首先准备工作要先申请创建百度账号、创建相对应用,获取API Key 和 Secret Key(创建成功后如下图:)
在创建应用之后,可以根据你需要完成的需求,领取免费的测试资源(如下图:)
在这里我就演示由本地上传的案例
1.准备pom文件
<!--用于解析返回json数据,案例中没用到--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.46</version></dependency><!-- Http请求 --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.5</version></dependency>
2.获取Access_token
由于Access_token也会过期(有效期为30天),为了更好的实现需求,我们可以每次获取最新的Access_token,获取的方式也非常的简单。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;import org.json.JSONObject;public class AccessTokenUtils {private static String APIKEY = "************************";private static String SecretKEY = "******************************";// 获取Token路径private static String PATH = "https://aip.baidubce.com/oauth/2.0/token?";public static String getAuth() {// 获取token地址String getAccessTokenUrl = PATH// 1. grant_type为固定参数+ "grant_type=client_credentials"// 2. 官网获取的 API Key+ "&client_id=" + APIKEY// 3. 官网获取的 Secret Key+ "&client_secret=" + SecretKEY;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);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;}
}
3.本地上传需要将图片转为Base64码,Url图片可以直接传网络地址
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;public class BaseImg64Utils {/*** 将一张本地图片转化成Base64字符串* @param imgPath 本地图片地址* @return 图片转化base64后再UrlEncode结果*/public static String getImageStrFromPath(String imgPath) {InputStream in = null;byte[] data = null;// 读取图片字节数组try {in = new FileInputStream(imgPath);data = new byte[in.available()];in.read(data);in.close();} catch (IOException e) {e.printStackTrace();}// 对字节数组Base64编码BASE64Encoder encoder = new BASE64Encoder();// 返回Base64编码过的字节数组字符串return encoder.encode(data).replaceAll("\r\n", "").replaceAll("\\+", "%2B");}
}
4.调用API接口的方法,获取识别结果
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;import com.store.utils.AccessTokenUtils;
import com.store.utils.BaseImg64Utils;public class XszOcrUtils {private static final String POST_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token="+ AccessTokenUtils.getAuth();//必传参数:id_card_side=frontfront:身份证含照片的一面 -back:身份证带国徽的一面 自动检测身份证正反面,如果传参指定方向与图片相反,支持正常识别,返回参数image_status字段为"reversed_side"/*** 识别本地图片的文字** @param path 本地图片地址* @return 识别结果,为json格式* @throws URISyntaxException URI打开异常* @throws IOException io流异常*/public static String checkFile(String path) throws URISyntaxException, IOException {File file = new File(path);if (!file.exists()) {throw new NullPointerException("图片不存在");}String image = BaseImg64Utils.getImageStrFromPath(path);String param = "image=" + image + "&id_card_side=front";return post(param);}/*** @param url 图片url* @return 识别结果,为json格式*/public static String checkUrl(String url) throws IOException, URISyntaxException {String param = "url=" + url;return post(param);}/*** 通过传递参数:url和image进行文字识别** @param param 区分是url还是image识别* @return 识别结果* @throws URISyntaxException URI打开异常* @throws IOException IO流异常*/private static String post(String param) throws URISyntaxException, IOException {// 开始搭建post请求HttpClient httpClient = HttpClientBuilder.create().build();HttpPost post = new HttpPost();URI url = new URI(POST_URL);post.setURI(url);// 设置请求头,请求头必须为application/x-www-form-urlencoded,因为是传递一个很长的字符串,不能分段发送post.setHeader("Content-Type", "application/x-www-form-urlencoded");StringEntity entity = new StringEntity(param);post.setEntity(entity);HttpResponse response = httpClient.execute(post);if (response.getStatusLine().getStatusCode() == 200) {String str;try {/* 读取服务器返回过来的json字符串数据 */str = EntityUtils.toString(response.getEntity());return str;} catch (Exception e) {e.printStackTrace();return null;}}return null;}public static void main(String[] args) throws URISyntaxException, IOException {String checkFile = checkFile("D:\\sfz.jpg");System.out.println("========" + checkFile);}
}
5.识别结果(解析之后就是这样)