java实现ocr功能(Tesseract OCR)

1、pom文件中引入依赖

复制代码
<dependency>
    <groupId>net.sourceforge.tess4j</groupId>
    <artifactId>tess4j</artifactId>
    <version>4.5.4</version>
</dependency>

2、下载语言库文件(不要放到resources下,可以放到项目所在目录下,在博主的主页资源菜单下可下载,也可自行在网上找资源下载)

参考目录结构(也可以放其他位置,只要代码能找到就行):

3、代码:

java 复制代码
@PostMapping("/ocr2")
@ApiOperationSupport(order = 3)
@ApiOperation(value = "识别图像2", notes = "上传图像")
public R<String> ocr2(@RequestBody MultipartFile file) throws Exception {
    Tesseract instance = new Tesseract();
    // 设置Tesseract的语言库路径
    ClassPathResource classPathResource = new ClassPathResource("/tessdata");
    String tessDataPath = classPathResource.getPath();
    instance.setDatapath(tessDataPath);
    instance.setLanguage("chi_sim");
    String ocrResult = "";
    File tfile = File.createTempFile("tempfile", file.getOriginalFilename());
    file.transferTo(tfile);
    ocrResult = instance.doOCR(tfile);
    return R.data(ocrResult);
}

4、测试接口(只能上传jpg文件)

测试时使用的图片

相关推荐
用户3521802454755 小时前
当 Prompt 学会"热更新":Spring Boot × Nacos3 AI 实战
java·spring boot·ai编程
东坡白菜8 小时前
破局全栈:一个前端开发的Java入门实战记录(1)
java·全栈
唐青枫8 小时前
Java Tomcat 实战指南:从 Servlet 容器到 Spring Boot 部署
java
wsaaaqqq8 小时前
roudan:自由选择实体、灵活操作数据、快速写入数据库的 Java 框架
java
plainGeekDev12 小时前
null 判断 → Kotlin 可空类型
android·java·kotlin
糖拌西瓜皮12 小时前
Java开发者视角:深入理解Node.js异步编程模型
java·后端·node.js
plainGeekDev12 小时前
getter/setter → Kotlin 属性
android·java·kotlin
一线大码12 小时前
Smart-Doc 的简单使用
java·后端·restful
MacroZheng14 小时前
Claude Code官方桌面端正式发布,夯爆了!
java·人工智能·后端