zouyu
2025-09-26 3fbbfcc8f509c352c58dc8a126220b49b72ed5a0
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package com.xindao.ocr.swingui.swing.utils;
 
import org.bytedeco.opencv.global.opencv_imgcodecs;
import org.bytedeco.opencv.global.opencv_imgproc;
import org.bytedeco.opencv.opencv_core.Mat;
import org.bytedeco.opencv.opencv_core.Size;
import org.springframework.web.multipart.MultipartFile;
 
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.util.Objects;
import java.util.Optional;
 
/**
 * @author sy
 * @date 2022/11/23 22:03
 */
public class ToFile {
 
    /**
     * MultipartFile转File
     * @param file
     * @return
     * @throws IOException
     */
    public static File multipartFiletoFile(MultipartFile file) throws IOException {
        File toFile = null;
        if((!file.equals("")) && (file.getSize() > 0)) {
            String filePath = "/tmp/img";
            if(!new File(filePath).exists()) {
                new File(filePath).mkdirs();
            }
            InputStream inputStream = file.getInputStream();
            String fileFullName = file.getOriginalFilename();
            String fileName = fileFullName.substring(0, fileFullName.lastIndexOf("."));
            String prefix = fileFullName.substring(fileFullName.lastIndexOf("."));
            toFile = new File(filePath + fileName + "_" + System.currentTimeMillis() + prefix);
            intputStreamToFile(inputStream, toFile);
            inputStream.close();
        }
        return toFile;
    }
 
    /**
     * 获取文件流
     * @param inputStream
     * @param file
     */
    private static void intputStreamToFile(InputStream inputStream, File file) {
        try (OutputStream outputStream = new FileOutputStream(file)) {
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 删除临时文件
     * @param file
     */
    public static void deleteTempFile(File file) {
        if(Optional.ofNullable(file).isPresent()) {
            File del = new File(file.toURI());
            del.delete();
        }
    }
 
    /**
     * 删除临时目录下的所有文件
     * @param cacheDir
     */
    public static void deleteTempFiles(File cacheDir) {
        //删除临时目录
        if (cacheDir.exists() && cacheDir.isDirectory()) {
            for (File tempFile : Objects.requireNonNull(cacheDir.listFiles())) {
                if (tempFile.isFile()) {
                    try {
                        Files.delete(tempFile.toPath());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
 
 
    /**
     * 保存图像到指定路径
     * @param image 图像对象
     * @param filePath 保存路径
     * @param formatName 图像格式(如 "png", "jpg")
     * @return 是否保存成功
     */
    public static boolean saveImage(BufferedImage image, String filePath, String formatName) {
        if (image == null || filePath == null || formatName == null) {
            System.err.println("参数不能为空");
            return false;
        }
 
        try {
            // 创建文件对象
            File outputFile = new File(filePath);
 
            // 确保父目录存在
            File parentDir = outputFile.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                parentDir.mkdirs(); // 递归创建目录
            }
 
            // 保存图片
            return ImageIO.write(image, formatName, outputFile);
        } catch (IOException e) {
            System.err.println("保存图片失败:" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 预处理图像以提高OCR识别率
     * @param inputPath 输入图像路径
     */
    public static void preprocessImage(String inputPath) {
        Mat src = opencv_imgcodecs.imread(inputPath);
        if (src.empty()) {
            System.err.println("无法读取图像: " + inputPath);
            return ;
        }
 
        // 1. 灰度化
        Mat gray = new Mat();
        opencv_imgproc.cvtColor(src, gray, opencv_imgproc.COLOR_BGR2GRAY);
 
        // 2. 轻量去噪(避免过度模糊H的边缘)
//        Mat blurred = new Mat();
//        opencv_imgproc.GaussianBlur(gray, blurred, new Size(1, 1), 0); // 缩小模糊核,保留字符细节
 
        // 3. 对比度增强(改用CLAHE,更精细控制对比度)
        Mat enhanced = new Mat();
        opencv_imgproc.createCLAHE(3, new Size(3, 3)).apply(gray, enhanced); // clipLimit调整对比度强度
 
//        // 4. 二值化(调整阈值参数,让H的轮廓更锐利)
//        Mat binary = new Mat();
//        opencv_imgproc.adaptiveThreshold(
//                enhanced,
//                binary,
//                255,
//                opencv_imgproc.ADAPTIVE_THRESH_GAUSSIAN_C,
//                opencv_imgproc.THRESH_BINARY_INV,
//                3,   // blockSize缩小,提升局部阈值精度
//                3     // C值调整,控制阈值偏移
//        );
//
//        // 5. 形态学操作(膨胀+腐蚀,让H的笔画更粗壮)
//        Mat kernel = opencv_imgproc.getStructuringElement(opencv_imgproc.MORPH_RECT, new Size(1, 1)); // 增大核尺寸
//        Mat morph = new Mat();
//        opencv_imgproc.dilate(binary, morph,kernel);   // 先膨胀(加粗字符)
//        opencv_imgproc.erode(morph, morph,kernel);    // 再腐蚀(修复膨胀后的边缘,保持字符形状)
 
        // 保存并释放资源
        opencv_imgcodecs.imwrite(inputPath, enhanced);
        src.release();
        gray.release();
//        blurred.release();
        enhanced.release();
//        binary.release();
//        kernel.release();
//        morph.release();
 
    }
 
}