# 图片处理

back

# 图片字节

返回顶部

/**
* 根据url地址获取图片信息
* @param urlPath 地址
* @return byte[]
*/
private static byte[] getBase64ByUrl(String urlPath) throws IOException {
    if (StringUtils.isBlank(urlPath)){
        return null;
    }
    final String defaultSuffix = "jpg";
    List<String> suffixes = Arrays.asList("png","jpg","gif","jpeg","bmp");
    String suffix = Optional.of(urlPath).filter(StringUtils::isNotBlank)
            .map(str -> StringUtils.substring(str,str.lastIndexOf(".")+1))
            .filter(suffixes::contains)
            .orElse(defaultSuffix);
    URL url = new URL(urlPath);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(RequestMethod.GET.name());
    conn.setConnectTimeout(5000);
    conn.setRequestProperty("Accept-Encoding", "identity");
    BufferedImage image=ImageIO.read(conn.getInputStream());
    ByteArrayOutputStream baso = new ByteArrayOutputStream();
    ImageIO.write(image,StringUtils.defaultIfBlank(suffix,"jpg"),baso);
    conn.disconnect();
    byte[] results = baso.toByteArray();
    baso.close();
    return results;

/**
* 获取本地图炮
* @param imgPath 地址
* @return byte[]
*/
private static byte[] getBase64ByLocal(String imgPath) throws IOException {
    String suffix = Optional.ofNullable(imgPath).filter(StringUtils::isNotBlank)
            .map(str -> StringUtils.substring(str,str.lastIndexOf(".")+1))
            .orElse(StringUtils.EMPTY);
    File file = new File(imgPath.trim());
    BufferedImage bi;
    bi = ImageIO.read(file);
    ByteArrayOutputStream baso = new ByteArrayOutputStream();
    ImageIO.write(bi,suffix,baso);
    return baso.toByteArray();
}
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
URL pathUrl = new URL(imgPath);
DataInputStream dataInputStream = new DataInputStream(pathUrl.openStream());
imgByte = IOUtils.toByteArray(dataInputStream);

File imgFile = ResourceUtils.getFile(imgPath);
FileInputStream fis = new FileInputStream(imgFile);
imgByte = IOUtils.toByteArray(fis);
1
2
3
4
5
6
7

# 图片合成

返回顶部

实例:项目中印章合成

// 获取印章
public static BufferedImage loadImageLocal(String imgName) {
        Assert.hasText(imgName,ResourceUtil.getValueByKey("09"));
        try {
            if (StringUtils.startsWith(imgName, SysConstants.HTTP_STR)){
                URL url = new URL(imgName);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod(RequestMethod.GET.name());
                conn.setConnectTimeout(5000);
                conn.setRequestProperty("Accept-Encoding", "identity");
                BufferedImage image=ImageIO.read(conn.getInputStream());
                conn.disconnect();
                return image;
            }
            return ImageIO.read(new File(imgName));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

/**
     * 把小图贴在大图右下角
     *
     * @param small 小图
     * @param big   大图
     * @return
     */
    public static BufferedImage modifyImagetogeter(BufferedImage small, BufferedImage big) {
        try {
            int w = big.getWidth();
            int h = big.getHeight();
//            BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
//            bufferedImage.createGraphics().drawImage(b,Double.valueOf (w*0.5).intValue(),Double.valueOf (h*0.5).intValue(),null);

            Graphics2D g = big.createGraphics();
//            g.drawImage(bufferedImage, bufferedImage.getWidth(),bufferedImage.getHeight(),
//                    w, h, null);
            //图片合成 按大图的宽度的30%进行合并
            int size = 0;
            if (w > h) {
                size = Double.valueOf(h * 0.2).intValue();
                g.drawImage(small.getScaledInstance(Double.valueOf(size).intValue(), Double.valueOf(size).intValue(), Image.SCALE_SMOOTH),
                        Double.valueOf(w - h * 0.25).intValue(), Double.valueOf(h * 0.75).intValue(), null);
            } else {
                size = Double.valueOf(w * 0.2).intValue();
                g.drawImage(small.getScaledInstance(Double.valueOf(size).intValue(),
                        Double.valueOf(size).intValue(), Image.SCALE_SMOOTH),
                        Double.valueOf(w * 0.75).intValue(), Double.valueOf(h - w * 0.25).intValue(), null);
            }
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return big;
    }

/**
     * 给传入的图片文件 进行盖章
     *
     * @param multipartFile 图片文件
     * @return 盖完章的图片文件
     */
    public static MultipartFile createImgWithSeal(MultipartFile multipartFile) {
        MultipartFile result = null;
        try {
            final String defaultSuffix = "jpg";
            List<String> suffixes = Arrays.asList("png","jpg","gif","jpeg","bmp");
            String suffix = Optional.ofNullable(multipartFile.getOriginalFilename()).filter(StringUtils::isNotBlank)
                    .map(str -> StringUtils.substring(str,str.lastIndexOf(".")+1))
                    .filter(suffixes::contains)
                    .orElse(defaultSuffix);
            BufferedImage big = ImageIO.read(multipartFile.getInputStream());
            String sealPath = UserUtil.getPdfSeal();
            BufferedImage small = loadImageLocal(sealPath);
            BufferedImage re = modifyImagetogeter(small, big);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            // 是否png图片能否正常关键在这里,suffix的值
            ImageIO.write(re, suffix, os);
            InputStream is = new ByteArrayInputStream(os.toByteArray());
            // 超过5M存磁盘
            final int tmpFileSize = 5242880;
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(tmpFileSize,new File(Objects.requireNonNull(
                    ClassUtils.getDefaultClassLoader().getResource("")).getPath() + "tmp"));
            FileItem fileItem = fileItemFactory.createItem("files",ContentType.APPLICATION_OCTET_STREAM.toString(),
                    false,multipartFile.getOriginalFilename());
            IOUtils.copy(is,fileItem.getOutputStream());
            // MockMultipartFile属于本地测试用-huting-20200318
//            result = new MockMultipartFile(multipartFile.getName(), multipartFile.getOriginalFilename(),
//                    ContentType.APPLICATION_OCTET_STREAM.toString(), is);
            result =  new CommonsMultipartFile(fileItem);
            return result;
        } catch (Exception e) {

        }
        return result;
    }
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

# 图片内容转文字

返回顶部

科技巨头 Google 一直在开发一个 OCR 引擎 Tesseract ,它从最初诞生到现在已有数十年的历史。它为许多语言提供了API,不过我们将专注于 Tesseract 的 Java API 。
很容易使用 Tesseract 来实现一个简单的功能。它主要用于读取计算机在黑白图片上生成的文字,并且结果的准确度较好。但这不是针对真实世界的文本

# maven依赖

back

<!-- https://mvnrepository.com/artifact/net.sourceforge.tess4j/tess4j -->
<dependency>
    <groupId>net.sourceforge.tess4j</groupId>
    <artifactId>tess4j</artifactId>
    <version>4.4.1</version>
</dependency>
1
2
3
4
5
6

# 光学字符识别

back

Tesseract tesseract = new Tesseract();
tesseract.setDatapath("E://DataScience//tessdata");
System.out.println(tesseract.doOCR(new File("...")));
1
2
3

# springboot实现

back

springboot实现

spring-boot-starter-webspring-boot-starter-thymeleaf依赖。然后我们手动导入Tesseract