czt
20 小时以前 9f6dacf7b39e5aeba37d8faf575c9e56d8cbe51a
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package com.fzzy.api.utils;
 
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
 
/**
 *
 */
@SuppressWarnings("restriction")
public class Base64Util {
 
    static BASE64Decoder decoder = new BASE64Decoder();
 
    public static String UTF_8 = "UTF-8";
 
    public static String BASE_IMG_START = "data:image/jpg;base64,";
 
    /**
     * 根据地址,把图片转换为Base64字符串
     * <p>
     * data:image/jpg;base64,
     *
     * @param diskFile
     * @return
     */
    public static String getImageStr(String diskFile) {
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(diskFile);
            data = new byte[in.available()];
            in.read(data);
            // in.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != in)
                    in.close();
            } catch (Exception e) {
            }
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return BASE_IMG_START + encoder.encode(data);
    }
 
    /**
     * 对字节数组字符串进行Base64解码并生成图片
     *
     * @param imgStr
     * @return
     */
    public static boolean generateImage(String imgStr, String diskFile) {
        if (imgStr == null)
            return false;
 
        if (imgStr.startsWith("data:")) {
            imgStr = imgStr.substring(BASE_IMG_START.length());
        }
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 生成jpeg图片
            out = new FileOutputStream(diskFile);
            out.write(b);
            out.flush();
            // out.close();
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (null != out)
                    out.close();
            } catch (Exception e) {
 
            }
        }
    }
 
    public static String encode2String(byte[] data) {
        BASE64Encoder encoder = new BASE64Encoder();
        return BASE_IMG_START + encoder.encode(data);
    }
 
 
    /**
     * 将Base64编码的数据转换为文件并保存到本地
     *
     * @param base64Data Base64编码的字符串数据
     * @param outputFilePath 输出文件的路径
     * @return 如果成功,返回保存的文件路径;否则返回null
     */
    public static String saveBase64ToFile(String base64Data, String outputFilePath) {
        try {
            // 移除可能存在的Base64数据前缀(例如data:image/png;base64,)
            if (base64Data.contains(";base64,")) {
                base64Data = base64Data.split(";base64,")[1];
            }
 
            // 解码Base64数据
            byte[] fileData = Base64.getDecoder().decode(base64Data);
 
            // 确保目录存在
            Path path = Paths.get(outputFilePath);
            Path parentDir = path.getParent();
            if (parentDir != null && !Files.exists(parentDir)) {
                Files.createDirectories(parentDir);
            }
 
            // 写入文件
            Files.write(path, fileData, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
 
            System.out.println("文件已成功保存至: " + outputFilePath);
            return outputFilePath;
 
        } catch (IllegalArgumentException e) {
            System.out.println("错误: 无效的Base64数据 - " + e.getMessage());
            return null;
        } catch (IOException e) {
            System.out.println("错误: 文件操作失败 - " + e.getMessage());
            return null;
        } catch (Exception e) {
            System.out.println("错误: 发生了未知错误 - " + e.getMessage());
            return null;
        }
    }
 
    /**
     * 将base64编码转换成PDF,保存
     *
     * @param base64sString 1.使用BASE64Decoder对编码的字符串解码成字节数组
     *                      2.使用底层输入流ByteArrayInputStream对象从字节数组中获取数据;
     *                      3.建立从底层输入流中读取数据的BufferedInputStream缓冲输出流对象;
     *                      4.使用BufferedOutputStream和FileOutputSteam输出数据到指定的文件中
     */
    public static void base64StringToPDF(String base64sString, String filePath, String fileName) {
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        BufferedInputStream bin = null;
        FileOutputStream fout = null;
        BufferedOutputStream bout = null;
        try {
            //将base64编码的字符串解码成字节数组
            byte[] bytes = decoder.decodeBuffer(base64sString);
            //apache公司的API
            //byte[] bytes = Base64.decodeBase64(base64sString);
            //创建一个将bytes作为其缓冲区的ByteArrayInputStream对象
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            //创建从底层输入流中读取数据的缓冲输入流对象
            bin = new BufferedInputStream(bais);
            //指定输出的文件
            File file = new File(filePath + fileName);
            //创建到指定文件的输出流
            fout = new FileOutputStream(file);
            //为文件输出流对接缓冲输出流对象
            bout = new BufferedOutputStream(fout);
 
            byte[] buffers = new byte[1024];
            int len = bin.read(buffers);
            while (len != -1) {
                bout.write(buffers, 0, len);
                len = bin.read(buffers);
            }
            //刷新此输出流并强制写出所有缓冲的输出字节,必须这行代码,否则有可能有问题
            bout.flush();
 
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bin.close();
                fout.close();
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}