简介

使用Java实现图片内容的实现功能,如验证码图片的读取

所用框架:Tess4j 项目地址:https://github.com/nguyenq/tess4j

整合使用

  1. 安装下载tessdata语言包,添加语言库

tessdata.zip

  1. 引入依赖:
1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.14.0</version>
</dependency>
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>4.5.4</version>
</dependency>
  1. 整合基本使用

定义配置类:

这里需要说明一下为什么这里地址是写死的,原本我也是使用的相对路径,使用相对路径在本地编译器上运行也是可以,没有问题的,但是当打jar包后再进行运行,就会有找不到库的问题。有些地方说java启动参数、修改打包范围什么的,但是都试过了,问题并不能解决,所以这里讲语言库的地址给写死了。

1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
public class TesseractOcrConfig {
@Bean
public Tesseract tesseract() {

Tesseract tesseract = new Tesseract();
// 设置训练数据文件夹路径
// tesseract.setDatapath("src/main/resources/tessdata");
tesseract.setDatapath("D:\\snail\\tessdata");
return tesseract;
}
}

识别代码:主要就是把需要进行识别的图片作为文件调用API进行识别就可以了,识别的效果不一定完全正确,这里以识别验证码为例。

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
/**
* 获取验证码
*/
private String getVerificationCode() {
String res = "";
String imageUrl = "一个验证码图片的链接";
URL url = null;
try {
url = new URL(imageUrl);
} catch (MalformedURLException e) {
log.error("获取验证码图片失败!{}", e.getMessage());
throw new RuntimeException(e);
}
try {
InputStream in = url.openStream();
Files.copy(in, Paths.get("downloaded.jpg"), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
log.error("验证码图片存储失败!{}", e.getMessage());
throw new RuntimeException(e);
}
File imageFile = new File("downloaded.jpg");
try {
res = tesseract.doOCR(imageFile);
} catch (TesseractException e) {
log.error("解析验证码图片内容失败!{}", e.getMessage());
throw new RuntimeException(e);
}
if (res.isEmpty()) {
log.error("解析验证码图片内容失败!");
throw new RuntimeException("解析验证码图片内容失败!");
} else {
return res.trim();
}
}

效果如下:

输出 3620