Tess4jClient.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package com.ruixuan.isc.utils;
  2. import io.minio.GetObjectArgs;
  3. import lombok.Data;
  4. import net.sourceforge.tess4j.ITesseract;
  5. import net.sourceforge.tess4j.Tesseract;
  6. import org.springframework.boot.context.properties.ConfigurationProperties;
  7. import org.springframework.stereotype.Component;
  8. import org.springframework.web.bind.annotation.RequestParam;
  9. import org.springframework.web.multipart.MultipartFile;
  10. import javax.imageio.ImageIO;
  11. import java.awt.image.BufferedImage;
  12. import java.io.ByteArrayInputStream;
  13. import java.io.ByteArrayOutputStream;
  14. import java.io.IOException;
  15. import java.io.InputStream;
  16. @Data
  17. @Component
  18. public class Tess4jClient {
  19. private static String DATA_PATH = "/data/webapp/RuiXuan-Cloud/tessdata";
  20. private static String LANGUAGE = "chi_sim";
  21. // 入参:图片流
  22. public String doOCR(BufferedImage image) throws Exception {
  23. //创建Tesseract对象
  24. ITesseract tesseract = new Tesseract();
  25. //设置中文字体库路径
  26. tesseract.setDatapath(DATA_PATH);
  27. //中文识别
  28. tesseract.setLanguage(DATA_PATH);
  29. //执行ocr识别
  30. String result = tesseract.doOCR(image);
  31. //替换回车和tal键 使结果为一行
  32. System.out.println(result.replaceAll(" ", ""));
  33. result = result.replaceAll("\\r|\\n", "-").replaceAll(" ", "");
  34. return result;
  35. }
  36. public String getWords(MultipartFile file) throws Exception {
  37. InputStream inputStream = file.getInputStream();
  38. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  39. byte[] buff = new byte[100];
  40. int rc = 0;
  41. while (true) {
  42. try {
  43. if (!((rc = inputStream.read(buff, 0, 100)) > 0)) break;
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. }
  47. byteArrayOutputStream.write(buff, 0, rc);
  48. }
  49. //从byte[]转换为butteredImage
  50. ByteArrayInputStream in = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
  51. BufferedImage imageFile = ImageIO.read(in);
  52. //识别图片的文字
  53. return doOCR(imageFile);
  54. //再结合敏感词过滤算法,审核图片中的文字是否包含敏感词
  55. }
  56. }