chengf
2025-10-28 2807cca4b6f2e8af204d798679dcee78e695ee28
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
package com.ruoyi.utils;
 
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
 
import java.io.*;
 
public class SaveImg {
    public static void saveByteImg(Mat src, String filePath) {
        bytesToFile(matToByte(src), filePath);
    }
 
    /**
     * mat转byte[]
     * @param mat 图片对象
     * @return
     */
    public static byte[] matToByte(Mat mat) {
        MatOfByte matOfByte = new MatOfByte();
        Imgcodecs.imencode(".jpg", mat, matOfByte);
        byte[] byteArray = matOfByte.toArray();
        return byteArray;
    }
 
    /**
     * byte to file
     * @param buffer
     * @param filePath
     */
    public static void bytesToFile(byte[] buffer, final String filePath){
 
        File file = new File(filePath);
        File parentDir = file.getParentFile();
 
        if (!parentDir.exists()) {
            parentDir.mkdirs();
            /*if (parentDir.mkdirs()) {
                System.out.println("文件夹已创建");
            } else {
                System.out.println("无法创建文件夹");
                return;
            }*/
        }
        OutputStream output = null;
        BufferedOutputStream bufferedOutput = null;
 
        try {
 
            output = new FileOutputStream(file);
 
            bufferedOutput = new BufferedOutputStream(output);
 
            bufferedOutput.write(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(null!=bufferedOutput){
                try {
                    bufferedOutput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
 
            if(null != output){
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}