wlzboy
2026-01-24 b2bd9fb71ee17d0ec73429f03dc87c87a0a38325
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package com.ruoyi.system.utils;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.ocr.AipOcr;
import com.ruoyi.system.config.BaiduOCRConfig;
 
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.io.File;
import java.util.HashMap;
import java.util.Map;
 
/**
 * 百度OCR工具类
 * 使用百度AI开放平台的OCR服务进行文字识别
 * 支持通用文字识别、手写体识别等多种识别类型
 * 
 * 使用示例:
 * // 通用文字识别
 * JSONObject result = BaiduOCRUtil.generalRecognize("path/to/image.jpg");
 * 
 * // 手写体识别
 * JSONObject result = BaiduOCRUtil.handwritingRecognize("path/to/image.jpg");
 */
@Component
@Slf4j
public class BaiduOCRUtil {
 
 
 
    private static BaiduOCRConfig staticBaiduOcrConfig;
 
    @Autowired
    public void setBaiduOcrConfig(BaiduOCRConfig baiduOcrConfig) {
        BaiduOCRUtil.staticBaiduOcrConfig = baiduOcrConfig;
    }
 
    /**
     * 获取百度OCR客户端实例
     * @return AipOcr客户端实例
     */
    private static AipOcr getClient() {
        AipOcr client = new AipOcr(staticBaiduOcrConfig.getAppId(), 
                                   staticBaiduOcrConfig.getApiKey(), 
                                   staticBaiduOcrConfig.getSecretKey());
 
        // 设置连接超时时间和socket超时时间
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
 
        return client;
    }
 
    /**
     * 通用文字识别(图片路径)
     * @param imagePath 图片路径
     * @return 识别结果
     */
    public static JSONObject generalRecognize(String imagePath) {
        try {
            AipOcr client = getClient();
            
            // 参数为图片路径
            HashMap<String, String> options = new HashMap<String, String>();
            options.put("language_type", "CHN_ENG"); // 识别语言类型
            options.put("detect_direction", "true"); // 是否检测图像朝向
            options.put("detect_language", "true"); // 是否检测语言
            options.put("probability", "true"); // 是否返回识别结果中每一行的置信度
            
            org.json.JSONObject res = client.basicGeneral(imagePath, options);
            log.info("百度OCR通用文字识别成功,图片路径: {}", imagePath);
            
            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("data", JSON.parseObject(res.toString()));
            result.put("content", extractContentFromBaiduResult(JSON.parseObject(res.toString())));
            
            return result;
            
        } catch (Exception e) {
            log.error("百度OCR通用文字识别失败: {}", e.getMessage(), e);
            
            JSONObject errorResult = new JSONObject();
            errorResult.put("success", false);
            errorResult.put("error", e.getMessage());
            
            return errorResult;
        }
    }
 
    /**
     * 通用文字识别(文件对象)
     * @param imageFile 图片文件对象
     * @return 识别结果
     */
    public static JSONObject generalRecognize(File imageFile) {
        try {
            AipOcr client = getClient();
            
            // 参数为图片文件
            HashMap<String, String> options = new HashMap<String, String>();
            options.put("language_type", "CHN_ENG");
            options.put("detect_direction", "true");
            options.put("detect_language", "true");
            options.put("probability", "true");
            
            // 读取文件字节数组或使用文件路径
            org.json.JSONObject res = client.basicGeneral(imageFile.getAbsolutePath(), options);
            log.info("百度OCR通用文字识别成功,文件名: {}", imageFile.getName());
            
            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("data", JSON.parseObject(res.toString()));
            result.put("content", extractContentFromBaiduResult(JSON.parseObject(res.toString())));
            
            return result;
            
        } catch (Exception e) {
            log.error("百度OCR通用文字识别失败: {}", e.getMessage(), e);
            
            JSONObject errorResult = new JSONObject();
            errorResult.put("success", false);
            errorResult.put("error", e.getMessage());
            
            return errorResult;
        }
    }
 
    /**
     * 通用文字识别(图片字节数组)
     * @param imageBytes 图片字节数组
     * @return 识别结果
     */
    public static JSONObject generalRecognize(byte[] imageBytes) {
        try {
            AipOcr client = getClient();
            
            HashMap<String, String> options = new HashMap<String, String>();
            options.put("language_type", "CHN_ENG");
            options.put("detect_direction", "true");
            options.put("detect_language", "true");
            options.put("probability", "true");
            
            org.json.JSONObject res = client.basicGeneral(imageBytes, options);
            log.info("百度OCR通用文字识别成功,字节数组长度: {}", imageBytes.length);
            
            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("data", JSON.parseObject(res.toString()));
            result.put("content", extractContentFromBaiduResult(JSON.parseObject(res.toString())));
            
            return result;
            
        } catch (Exception e) {
            log.error("百度OCR通用文字识别失败: {}", e.getMessage(), e);
            
            JSONObject errorResult = new JSONObject();
            errorResult.put("success", false);
            errorResult.put("error", e.getMessage());
            
            return errorResult;
        }
    }
 
    /**
     * 高精度文字识别
     * @param imagePath 图片路径
     * @return 识别结果
     */
    public static JSONObject accurateRecognize(String imagePath) {
        try {
            AipOcr client = getClient();
            
            HashMap<String, String> options = new HashMap<String, String>();
            options.put("recognize_granularity", "big"); // 是否定位单字符位置
            options.put("language_type", "CHN_ENG");
            options.put("detect_direction", "true");
            options.put("detect_language", "true");
            options.put("vertexes_location", "true"); // 是否返回文字外接多边形顶点位置
            options.put("probability", "true");
            
            org.json.JSONObject res = client.accurateGeneral(imagePath, options);
            log.info("百度OCR高精度文字识别成功,图片路径: {}", imagePath);
            
            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("data", JSON.parseObject(res.toString()));
            result.put("content", extractContentFromBaiduResult(JSON.parseObject(res.toString())));
            
            return result;
            
        } catch (Exception e) {
            log.error("百度OCR高精度文字识别失败: {}", e.getMessage(), e);
            
            JSONObject errorResult = new JSONObject();
            errorResult.put("success", false);
            errorResult.put("error", e.getMessage());
            
            return errorResult;
        }
    }
 
    /**
     * 手写体识别
     * @param imagePath 图片路径
     * @return 识别结果
     */
    public static JSONObject handwritingRecognize(String imagePath) {
        try {
            AipOcr client = getClient();
            
            // 手写体识别参数
            HashMap<String, String> options = new HashMap<String, String>();
            options.put("language_type", "CHN_ENG");
            
            org.json.JSONObject res = client.handwriting(imagePath, options);
            log.info("百度OCR手写体识别成功,图片路径: {}", imagePath);
            
            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("data", JSON.parseObject(res.toString()));
            result.put("content", extractContentFromBaiduResult(JSON.parseObject(res.toString())));
            
            return result;
            
        } catch (Exception e) {
            log.error("百度OCR手写体识别失败: {}", e.getMessage(), e);
            
            JSONObject errorResult = new JSONObject();
            errorResult.put("success", false);
            errorResult.put("error", e.getMessage());
            
            return errorResult;
        }
    }
 
    /**
     * 手写体识别(文件对象)
     * @param imageFile 图片文件对象
     * @return 识别结果
     */
    public static JSONObject handwritingRecognize(File imageFile) {
        try {
            AipOcr client = getClient();
            
            HashMap<String, String> options = new HashMap<String, String>();
            options.put("language_type", "CHN_ENG");
            
            org.json.JSONObject res = client.handwriting(imageFile.getAbsolutePath(), options);
            log.info("百度OCR手写体识别成功,文件名: {}", imageFile.getName());
            
            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("data", JSON.parseObject(res.toString()));
            result.put("content", extractContentFromBaiduResult(JSON.parseObject(res.toString())));
            
            return result;
            
        } catch (Exception e) {
            log.error("百度OCR手写体识别失败: {}", e.getMessage(), e);
            
            JSONObject errorResult = new JSONObject();
            errorResult.put("success", false);
            errorResult.put("error", e.getMessage());
            
            return errorResult;
        }
    }
 
    /**
     * 身份证识别
     * @param imagePath 图片路径
     * @param isFront true为正面,false为反面
     * @return 识别结果
     */
    public static JSONObject idCardRecognize(String imagePath, boolean isFront) {
        try {
            AipOcr client = getClient();
            
            HashMap<String, String> options = new HashMap<String, String>();
            String idCardSide = isFront ? "front" : "back";
            
            org.json.JSONObject res = client.idcard(imagePath, idCardSide, options);
            log.info("百度OCR身份证识别成功,图片路径: {},方向: {}", imagePath, idCardSide);
            
            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("data", JSON.parseObject(res.toString()));
            
            return result;
            
        } catch (Exception e) {
            log.error("百度OCR身份证识别失败: {}", e.getMessage(), e);
            
            JSONObject errorResult = new JSONObject();
            errorResult.put("success", false);
            errorResult.put("error", e.getMessage());
            
            return errorResult;
        }
    }
 
    /**
     * 银行卡识别
     * @param imagePath 图片路径
     * @return 识别结果
     */
    public static JSONObject bankCardRecognize(String imagePath) {
        try {
            AipOcr client = getClient();
            
            org.json.JSONObject res = client.bankcard(imagePath, new HashMap<String, String>());
            log.info("百度OCR银行卡识别成功,图片路径: {}", imagePath);
            
            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("data", JSON.parseObject(res.toString()));
            
            return result;
            
        } catch (Exception e) {
            log.error("百度OCR银行卡识别失败: {}", e.getMessage(), e);
            
            JSONObject errorResult = new JSONObject();
            errorResult.put("success", false);
            errorResult.put("error", e.getMessage());
            
            return errorResult;
        }
    }
 
    /**
     * 营业执照识别
     * @param imagePath 图片路径
     * @return 识别结果
     */
    public static JSONObject businessLicenseRecognize(String imagePath) {
        try {
            AipOcr client = getClient();
            
            HashMap<String, String> options = new HashMap<String, String>();
            
            org.json.JSONObject res = client.businessLicense(imagePath, options);
            log.info("百度OCR营业执照识别成功,图片路径: {}", imagePath);
            
            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("data", JSON.parseObject(res.toString()));
            
            return result;
            
        } catch (Exception e) {
            log.error("百度OCR营业执照识别失败: {}", e.getMessage(), e);
            
            JSONObject errorResult = new JSONObject();
            errorResult.put("success", false);
            errorResult.put("error", e.getMessage());
            
            return errorResult;
        }
    }
 
    /**
     * 从百度OCR结果中提取文本内容
     * @param result 百度OCR返回的结果(fastjson格式)
     * @return 提取的文本内容
     */
    private static String extractContentFromBaiduResult(JSONObject result) {
        StringBuilder content = new StringBuilder();
        
        if (result.containsKey("words_result") && result.getJSONArray("words_result") != null) {
            JSONArray wordsResult = result.getJSONArray("words_result");
            for (int i = 0; i < wordsResult.size(); i++) {
                JSONObject wordResult = wordsResult.getJSONObject(i);
                if (wordResult.containsKey("words")) {
                    content.append(wordResult.getString("words")).append("\n");
                }
            }
        }
        
        return content.toString().trim();
    }
 
    /**
     * 从识别结果中提取目标字段(金额、日期、备注等)
     * @param ocrResult OCR识别的原始结果
     * @return 提取后的目标字段
     */
    public static java.util.Map<String, String> extractTargetFields(JSONObject ocrResult) {
        java.util.Map<String, String> extracted = new java.util.HashMap<>();
 
        // 校验OCR结果是否有效
        if (!ocrResult.containsKey("success") || !ocrResult.getBooleanValue("success")) {
            extracted.put("error", ocrResult.getString("error"));
            return extracted;
        }
 
        // 获取识别的文字内容
        String content = ocrResult.getString("content");
        if (content == null || content.isEmpty()) {
            extracted.put("error", "OCR识别结果为空");
            return extracted;
        }
 
        // 在内容中查找特定关键词
        String[] lines = content.split("\n");
        for (String line : lines) {
            line = line.trim();
            
            // 查找金额相关信息
            if (line.contains("金额") || line.contains("合计") || line.contains("总计") || line.matches(".*\\d+\\.\\d{2}.*")) {
                if (!extracted.containsKey("totalAmount")) {
                    extracted.put("totalAmount", line);
                }
            }
            
            // 查找日期相关信息
            if (line.contains("日期") || line.matches(".*\\d{4}[-/年]\\d{1,2}[-/月]\\d{1,2}.*")) {
                if (!extracted.containsKey("date")) {
                    extracted.put("date", line);
                }
            }
            
            // 查找备注相关信息
            if (line.contains("备注") || line.contains("说明")) {
                if (!extracted.containsKey("remark")) {
                    extracted.put("remark", line);
                }
            }
        }
 
        // 如果没有找到特定字段,返回全文
        if (extracted.isEmpty()) {
            extracted.put("fullText", content);
        }
 
        return extracted;
    }
}