Spring Boot 集成百度智能云 OCR

一、免费获取密钥

  1. 打开 百度智能云 - 文字识别

  2. 注册 → 创建应用 → 拿到 API KeySecret Key

  3. 每月有 免费调用额度,个人 / 小项目完全够用

二、Maven 依赖

xml 复制代码
<!-- 百度OCR SDK -->
<dependency>
    <groupId>com.baidu.aip</groupId>
    <artifactId>java-sdk</artifactId>
    <version>4.16.18</version>
</dependency>

三、Ocr工具类

java 复制代码
import com.baidu.aip.ocr.AipOcr;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 百度OCR工具类
 * 使用单例模式持久化AipOcr客户端,避免重复创建
 */
public class BaiduOcrUtil {

    // 替换成你自己的密钥
    private static final String APP_ID = "xxxxxx";
    private static final String API_KEY = "xxxxxxxxxxxxx";
    private static final String SECRET_KEY = "xxxxxxxxxxxx";

    // 单例客户端,线程安全
    private static volatile AipOcr client;

    /**
     * 获取AipOcr客户端实例(单例模式)
     * @return AipOcr客户端
     */
    private static AipOcr getClient() {
        if (client == null) {
            synchronized (BaiduOcrUtil.class) {
                if (client == null) {
                    client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
                    // 可选:设置连接超时和socket超时时间(毫秒)
                    client.setConnectionTimeoutInMillis(2000);
                    client.setSocketTimeoutInMillis(60000);
                }
            }
        }
        return client;
    }

    /**
     * 识别图片URL中的文字
     * @param imageUrl 图片URL地址
     * @return 拼接后的完整文本
     */
    public static String recognizeText(String imageUrl) {
        if (imageUrl == null || imageUrl.trim().isEmpty()) {
            return "";
        }

        try {
            // 获取单例客户端
            AipOcr ocrClient = getClient();
            
            // 设置参数
            HashMap<String, String> options = new HashMap<>();
            // 是否检测朝向
            options.put("detect_direction", "true");
            // 是否识别语言
            options.put("language_type", "CHN_ENG");

            // 核心方法:直接识别图片链接
            JSONObject res = ocrClient.basicGeneralUrl(imageUrl, options);
            
            // 将 words 结果拼接成一条字符串并返回
            return concatenateWords(res);
        } catch (Exception e) {
            throw new RuntimeException("OCR识别失败: " + e.getMessage(), e);
        }
    }

    /**
     * 将 OCR 识别结果中的 words 拼接成完整字符串
     * @param ocrResult OCR 识别结果的 JSONObject
     * @return 拼接后的完整文本
     */
    public static String concatenateWords(JSONObject ocrResult) {
        if (ocrResult == null || !ocrResult.has("words_result")) {
            return "";
        }
        
        JSONArray wordsResult = ocrResult.getJSONArray("words_result");
        
        // 使用 Stream API 拼接所有 words
        return IntStream.range(0, wordsResult.length())
                .mapToObj(i -> wordsResult.getJSONObject(i).getString("words"))
                .collect(Collectors.joining("\n"));
    }
}

可参考官方技术文档