windows 版
下载地址:https://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr-w64-setup-v5.3.0.20221214.exe
中文简体语言包下载:https://raw.githubusercontent.com/tesseract-ocr/tessdata/main/chi_sim.traineddata
操作
1、下载两个文件;
2、双击安装exe文件;
3、把安装根目录配置到 环境变量 Path中 ;
4、语言包 chi_sim.traineddata 放到安装目录的 tessdata 文件夹下;
5、cmd tesseract -v 验证安装结果;
6、系统编码集成:
java maven项目 引入 包
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>5.13.0</version> <!-- 建议使用最新稳定版 -->
</dependency>
编码:
import jakarta.annotation.PostConstruct;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
/**
* 图片文字识别工具类
*/
@Component
public class OcrUtils {
@Value("${tesseract.datapath}")
private String dataPathConfig;
private static String dataPath;
@PostConstruct
private void init() {
dataPath = dataPathConfig;
}
/**
* 识别图片文件中的文字(MultipartFile 入参)
*
* @param file 上传的图片文件
* @return 识别出的文字内容
* @throws IOException 图片读取失败时抛出
*/
public static String recognizeText(MultipartFile file) throws IOException {
try (InputStream is = file.getInputStream()) {
BufferedImage image = ImageIO.read(is);
if (image == null) {
throw new IOException("无法解析图片,请确认文件格式正确");
}
ITesseract instance = new Tesseract();
instance.setDatapath(dataPath);
instance.setLanguage("chi_sim");
return instance.doOCR(image).replace(" ", "").replace("\n", "");
} catch (TesseractException e) {
System.err.println("OCR识别失败: " + e.getMessage());
return "";
}
}
/**
* 识别 BufferedImage 图片对象中的文字
*/
public static String recognizeImage(File image, String language) {
ITesseract instance = new Tesseract();
instance.setDatapath(dataPath);
instance.setLanguage(language);
try {
return instance.doOCR(image);
} catch (TesseractException e) {
System.err.println("OCR识别失败: " + e.getMessage());
return "";
}
}
}
亲测,可用