springboot实现调用百度ocr实现身份识别+二要素校验

一、技术选型

OCR服务:推荐使用百度AI

二、实现

1.注册一个服务

百度智能云控制台https://console.bce.baidu.com/ai-engine/ocr/overview/index?_=1742309417611

填写完之后可以获取到app-idapiKeySecretKey这三个后面文件配置会用到

2、导入依赖

XML 复制代码
        <!-- Spring Boot Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.6.13</version>
        </dependency>

        <!-- 百度AI SDK(示例) -->
        <dependency>
            <groupId>com.baidu.aip</groupId>
            <artifactId>java-sdk</artifactId>
            <version>4.16.13</version>
        </dependency>
        <!--json依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.40</version>
        </dependency>

3、配置文件

XML 复制代码
spring:
  servlet:
    multipart:
      max-request-size: 10MB # 文件上传最大值
      max-file-size: 10MB # 单个文件最大值
baidu:
  ai:
    app-id: ***** 换成自己的
    secret-key: ***** 换成自己的
    api-key: ***** 换成自己的

4、编写OCR工具类

java 复制代码
import com.baidu.aip.ocr.AipOcr;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Component
public class OcrService {

    @Value("${baidu.ai.app-id}")
    private String appId;

    @Value("${baidu.ai.api-key}")
    private String apiKey;

    @Value("${baidu.ai.secret-key}")
    private String secretKey;

    public Map<String, String> recognizeIdCard(MultipartFile file, boolean isFront) throws Exception {
        AipOcr client = new AipOcr(appId, apiKey, secretKey);

        // 读取图片字节
        byte[] imgData = file.getBytes();

        // 设置身份证正反面
        String idCardSide = isFront ? "front" : "back";

        // 设置其他识别选项(如果有)
        HashMap<String, String> options = new HashMap<String, String>();
        // 可以在这里添加其他选项,例如:
        // options.put("detect_direction", "true"); // 检测图像朝向
        // 调用身份证识别接口
        JSONObject res = client.idcard(imgData, idCardSide, options);

        // 检查返回结果
        if (res == null || !res.has("words_result")) {
            throw new Exception("OCR 识别失败: 返回结果为空或不包含 words_result");
        }

        // 解析结果
        Map<String, String> result = new HashMap<String, String>();
        JSONObject words = res.getJSONObject("words_result");

        // 根据正反面提取不同字段
        if (isFront) {
            result.put("姓名", words.optString("姓名", ""));
            result.put("性别", words.optString("性别", ""));
            result.put("民族", words.optString("民族", ""));
            result.put("出生日期", words.optString("出生年月日", ""));
            result.put("住址", words.optString("住址", ""));
            result.put("身份证号", words.optString("公民身份号码", ""));
        } else {
            result.put("签发机关", words.optString("签发机关", ""));
            result.put("有效期限", words.optString("失效日期", ""));
        }

        return result;
    }
}

5、文件上传接口

java 复制代码
import com.alibaba.fastjson.JSON;
import com.cykj.service.OcrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/idcard")
/**
 * 身份证识别控制器
 * 提供身份证图片上传和识别功能
 */
public class IdCardController {

    @Autowired
    private OcrService ocrService;

    /**
     * 上传身份证图片并进行识别
     * 
     * @param frontFile 身份证正面图片
     * @param backFile 身份证反面图片
     * @return 身份证信息的Map,包括正面和反面的识别结果
     */
    @PostMapping("/upload")
    public ResponseEntity<?> uploadIdCard(
            @RequestParam("frontFile") MultipartFile frontFile,
            @RequestParam("backFile") MultipartFile backFile) {
        System.out.println(frontFile);
        System.out.println(backFile);
        try {
            // 识别正面信息
            Map<String, String> frontInfo = ocrService.recognizeIdCard(frontFile, true);
            System.out.println("Front Info: " + frontInfo);

            // 识别反面信息
            Map<String, String> backInfo = ocrService.recognizeIdCard(backFile, false);
            System.out.println("Back Info: " + backInfo);

            // 合并结果
            Map<String, String> combined = new HashMap<String, String>();
            combined.putAll(frontInfo);
            combined.putAll(backInfo);
            // 身份证校验(示例)
            String idNumberJson = combined.get("身份证号");
            //解析获取身份证号
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(idNumberJson);
            String idNumber = jsonObject.getString("words");
            if (!validateIdCard(idNumber)) {
                return ResponseEntity.badRequest().body("身份证号校验失败");
            }

            return ResponseEntity.ok(combined);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("识别失败: " + e.getMessage());
        }
    }

    /**
     * 简单身份证号校验(正则表达式)
     * 
     * @param idNumber 身份证号码字符串
     * @return 校验通过返回true,否则返回false
     */
    private boolean validateIdCard(String idNumber) {
        String regex = "^[1-9]\\d{5}(19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[\\dXx]$";
        return idNumber != null && idNumber.matches(regex);
    }
}

三、前端写个测试页面

这边的action路径要改成自己的路径

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://localhost:8086/api/idcard/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="frontFile" accept="image/*" required>
    <input type="file" name="backFile" accept="image/*" required>
    <button type="submit">上传并识别</button>
</form>
</body>
</html>

第一张为身份证正面(人)

第二张上传为身份证反面(国徽那面)

测试成功在页面和控制台都可以看见自己提取出来的信息就成功啦!

四、二要素校验

身份证上传也不能保证信息准确,毕竟还可以进行p图技术进行修改嘛

为了保证信息的正确,就得要引入二要素校验==》对姓名和身份证号码进行校验

(1)配置

https://www.apispace.com/explore/service

打开网址

首次购买有20次的免费使用!!! ,购买完如下~

往下滑可以看见主要的代码

(2)代码实现

java 复制代码
/**
     * 二要素校验
     * @param idNumber 身份证
     * @param realname 姓名
     * @return true则为一致,匹配正确
     * @throws IOException
     */
    private boolean validateIdCardAndName(String idNumber, String realname) throws IOException {
        // 示例:判断身份证号和姓名是否匹配
        OkHttpClient client = new OkHttpClient();
        //校验身份和姓名是否匹配 ==》二要素校验
        RequestBody body = RequestBody.create(okhttp3.MediaType.get("application/x-www-form-urlencoded"),
                "realname=" + realname + "&idcard=" + idNumber
        );
        //下面的addHeader和url都可以在上面购买完可以看见信息
        Request request = new Request.Builder()
                .url("换成自己的!!!!!!!!!!")
                .method("POST", body)
                .addHeader("X-APISpace-Token", "换成自己的!!!!!!!!!!")
                .build(); // 移除重复的 Content-Type 头
        Response response = client.newCall(request).execute();
        //System.out.println(response.body().string());
        //打印出来的{"requestId":"f20067dac6633685bd348f9e388b","data":{"valid":false,"incorrect":101,"message":"不一致"},"code":0,"message":"success"}
        if (response.code() != 200) {
            return false;
        }
        if (response.body() == null) {
            return false;
        }
        try {
            JSONObject responseJson = JSON.parseObject(response.body().string());
            if (responseJson.containsKey("data") && responseJson.getJSONObject("data").containsKey("message")) {
                JSONObject dataJson = responseJson.getJSONObject("data");
                String dataMessage = dataJson.getString("message");
                return "一致".equals(dataMessage);
            } else {
                System.out.println("响应缺少必要字段");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
java 复制代码
// 获取姓名
            String nameInfo = combined.get("姓名");
            JSONObject nameJson = JSON.parseObject(nameInfo);
            String realname = nameJson.getString("words");
            //校验姓名和身份证是否匹配
            boolean validateIdCardAndName = validateIdCardAndName(idNumber, realname);
            if (!validateIdCardAndName){
                //说明当前身份证于当前姓名不匹配
                return ResponseEntity.badRequest().body("姓名和身份不匹配,请检查填写信息是否正确");
            }

完事~

相关推荐
2301_7644413315 小时前
olmOCR大模型:支持结构化精准提取复杂PDF文件内容
python·pdf·ocr
沉到海底去吧Go1 天前
分享:图片识别改名,能识别图片中的文字并批量改名的工具,用WPF和阿里云来完成
ocr·wpf·批量图片区域识别改名
zzhongcy1 天前
搭建自己的OCR服务
ocr
编程咕咕gu-1 天前
Python OCR文本识别详细步骤及代码示例
人工智能·python·ocr·python基础·python教程
幸福清风2 天前
【OCR】使用Umi-OCR进行PDF文档的光学字符识别
pdf·ocr
Macdo_cn2 天前
PDF Reader Pro for Mac v4.9.0 PDF编辑/批注/OCR/转换工具 支持M、Intel芯片
pdf·ocr
熊文豪3 天前
【实用部署教程】olmOCR智能PDF文本提取系统:从安装到可视化界面实现
ocr·pdf文本提取·ai2工具·文本智能提取·gradio界面开发·深度学习应用·olmocr
qyr204 天前
百度OCR调用记录
ocr
冲上云霄的Jayden6 天前
基于CPU使用paddlex OCR识别图片内容
python·ocr·conda·paddlepaddle·paddlex·银行回执·单据提取