xiaoyong931011
2022-03-16 dca3e301410be4aee5a7895a1c2c1bbf90f3d03b
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
package com.xcong.excoin.utils;
 
 
import cn.hutool.core.util.StrUtil;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
import java.io.*;
 
public class ImageUtils {
 
    public static boolean base64ToImg(String base64Str, String imgPath) {
        // 图像数据为空
        if (StrUtil.isBlank(base64Str)) {
            return false;
        }
 
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(base64Str);
            for (int i = 0; i < bytes.length; ++i) {
                // 调整异常数据
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgPath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
 
    public static String imgToBase64(String imgPath) {
        byte[] data = null;
 
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(data);
    }
 
 
    public static void main(String[] args) {
        base64ToImg(imgToBase64("/Users/helius/Pictures/123.jpg"), "/Users/helius/Desktop/123.jpg");
    }
}