大家好,我是 程序员码递夫 。
今天给大家分享的是 JAVA后台如何调用百度的身份证识别API。
1、前言
我们做APP开发时常遇到 身份证认证或资质认证的 需求, 通过上传身份证照片是个常用的操作, 后台对上传的身份证照信息进行识别,并提取关键的实名信息保存入库。借助百度的开放平台,可轻松实现 身份证信息的提取。
2、百度的开放平台
百度的AI开放平台(https://ai.baidu.com/),向我们提供了 卡证文字识别的功能调用,可以结构化识别身份证、银行卡、营业执照等常用卡片及证照,支持营业执照信息的准确性核验;还可使用iOCR、 EasyDL OCR 自定义平台,定制个性化识别模型。广泛适用于身份认证、金融开户、征信评估等业务场景。接口调用简单,对开发者友好,有免费的测试资源资源领取。个人认证 200 次,企业认证 500 次。
2.1、注册或登录百度开放平台
浏览器打开 https://ai.baidu.com/ 网址, 选择注册或登录
2.2、领取免费测试资源
进入控制台,选择文字识别模块, 在“操作指引”里的 免费尝鲜 选择 去领取,
选择 卡证OCR 的 身份证识别 即可
2.3、创建应用获取密钥
在“操作指引”里的 创建应用 选择 去创建,
输入应用的名称、文字识别选择 身份证识别, 输入简单的应用描述,点创建即可
然后在应用列表中,可以看到我们刚才创建的应用,其中APP ID、 API Key、Secret Key这三个是调用百度api的必要参数,后面代码会用到这些。
3、后端代码
这里将以 java 代码为例进行讲解。
3.1、使用maven依赖
<!-- baidu OCR Java SDK -->
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.16.18</version>
</dependency>
3.2、简单例子代码
import java.util.*;
import org.json.JSONObject;
import com.baidu.aip.ocr.AipOcr;
public class Sample {
//设置APPID/AK/SK
public static final String APP_ID = "你的 App ID";
public static final String API_KEY = "你的 Api Key";
public static final String SECRET_KEY = "你的 Secret Key";
public static void main(String[] args) {
// 初始化一个AipOcr
AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
// 调用接口
String path = "c:\test.jpg"; //身份证照片
JSONObject res = client.basicGeneral(path, new HashMap<String, String>());
System.out.println(res.toString(2));
}
}
3.3、身份证识别 JSON返回示例
{
"log_id": 2648325511,
"direction": 0,
"image_status": "normal",
"idcard_type": "normal",
"edit_tool": "Adobe Photoshop CS3 Windows",
"words_result": {
"住址": {
"location": {
"left": 267,
"top": 453,
"width": 459,
"height": 99
},
"words": "南京市江宁区弘景大道3889号"
},
"公民身份号码": {
"location": {
"left": 443,
"top": 681,
"width": 589,
"height": 45
},
"words": "330881199904173914"
},
"出生": {
"location": {
"left": 270,
"top": 355,
"width": 357,
"height": 45
},
"words": "19990417"
},
"姓名": {
"location": {
"left": 267,
"top": 176,
"width": 152,
"height": 50
},
"words": "伍云龙"
},
"性别": {
"location": {
"left": 269,
"top": 262,
"width": 33,
"height": 52
},
"words": "男"
},
"民族": {
"location": {
"left": 492,
"top": 279,
"width": 30,
"height": 37
},
"words": "汉"
}
},
"words_result_num": 6
}
大家也可以参考官方的代码(https://ai.baidu.com/ai-doc/OCR/Ikibizxql)进行更进一步的了解。
3.4、封装后的代码
根据自己项目的需要,自己封装了一个静态类,便于功能调用。
import com.baidu.aip.ocr.AipOcr;
import com.example.springboot.common.Constants;
import com.example.springboot.common.Result;
import com.example.springboot.entity.IdCard;
import org.json.JSONObject;
import java.util.HashMap;
/**
* @Description 百度身份证OCR识别
* @Author wx_madaogongcheng
* @Date
*/
public class IdCardOCR {
/**
* 卡面
*/
public interface CardSide {
/** 正面*/
String FRONT_SIDE = "front";
/** 背面*/
String BACK_SIDE = "back";
}
public static Boolean getEnable() {
return ENABLE;
}
public static void setEnable(Boolean enable) {
IdCardOCR.ENABLE = enable;
}
/** 功能是否启用 */
private static Boolean ENABLE = false;
/** 百度 app id */
private static String APP_ID = "";
/** 百度 api key */
private static String API_KEY = "";
/** 百度 secret key */
private static String SECRET_KEY = "";
public static String getAppId() {
return APP_ID;
}
public static void setAppId(String appId) {
APP_ID = appId;
}
public static String getApiKey() {
return API_KEY;
}
public static void setApiKey(String apiKey) {
API_KEY = apiKey;
}
public static String getSecretKey() {
return SECRET_KEY;
}
public static void setSecretKey(String secretKey) {
SECRET_KEY = secretKey;
}
/**
* 初始化
* @param enable
* @param appId
* @param apiKey
* @param secretKey
* @return
*/
public static boolean init(Boolean enable, String appId, String apiKey, String secretKey) {
setEnable(enable);
setAppId(appId);
setApiKey(apiKey);
setSecretKey(secretKey);
return true;
}
/**
* 获取身份证信息
* @param image 身份证图片完整路径
* @param cardSide 卡面(正面,反面)
* @return
*/
public static Result getIdCardInfo(String image, String cardSide ) {
try{
if (!ENABLE) {
return Result.error(Constants.CODE_600, "获取身份证信息失败,OCR识别身份证功能未启用");
}
IdCard idcard = new IdCard();
// 初始化一个AipOcr
AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
// 传入可选参数调用接口
HashMap<String, String> options = new HashMap<String, String>();
options.put("detect_direction", "true");
options.put("detect_risk", "false");
// 参数为本地图片路径
JSONObject res = client.idcard(image, cardSide, options);
if (null!=res && res.getInt("words_result_num")>0) {
//识别到结果
JSONObject words_result = res.getJSONObject("words_result");
if (cardSide.equalsIgnoreCase(CardSide.FRONT_SIDE)) {
idcard.setName(words_result.getJSONObject("姓名").getString("words"));
idcard.setBirth(words_result.getJSONObject("出生").getString("words"));
idcard.setIdcard(words_result.getJSONObject("公民身份号码").getString("words") );
idcard.setGender(words_result.getJSONObject("性别").getString("words") );
idcard.setNation(words_result.getJSONObject("民族").getString("words") );
}else {
idcard.setIssueOrg(words_result.getJSONObject("签发机关").getString("words"));
idcard.setIssueDate(words_result.getJSONObject("签发日期").getString("words"));
idcard.setExpiringDate(words_result.getJSONObject("失效日期").getString("words") );
}
return Result.success(idcard);
}else {
return Result.error(Constants.CODE_600, "获取身份证信息失败,请检查图片是否正确");
}
}catch (Exception ex){
ex.printStackTrace();
return Result.error(Constants.CODE_500, "获取身份证信息发生异常.原因=" + ex.getMessage());
}
}
}
3.5、测试代码
@SpringBootTest
class BaiduOcrTest {
@Value("${baidu.app-id}")
private String appId = ""; //百度 app id
@Value("${baidu.api-key}")
private String apiKey = ""; //百度 api key
@Value("${baidu.secret-key}")
private String secretKey = ""; //百度 secret key
@Test
public void testIdCard() {
System.out.println("----- 测试百度ocr识别身份证 开始------");
IdCardOCR.init(true,appId, apiKey, secretKey);
String image = "E:\\idcard.jpg";
Result retIdCard = IdCardOCR.getIdCardInfo(image, IdCardOCR.CardSide.FRONT_SIDE);
if (retIdCard.getCode().equalsIgnoreCase(Constants.OK)) {
System.out.println("身份证识别结果:");
System.out.println(((IdCard)retIdCard.getData()).toString());
}else {
System.out.println(retIdCard.getMsg());
}
System.out.println("----- 测试百度ocr识别身份证 结束------");
}
}
4、后记
百度文字识别接口调用简单,识别对象丰富,对开发者友好, 当你学会了身份证识别, 其他的车牌识别、营业执照识别等也可以手到擒来了。
还不清楚的,可以看官方文档,都会找到答案的。