fwq
2023-12-11 43d11becdfc0d7af00b10e91b962cd0c4738bbf1
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
package com.hx.util;
 
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
import java.io.*;
 
/**
 * 图片和base64字符转换工具
 * @USER: fhx
 * @DATE: 2023/4/6
 **/
public class ImageBase64Util {
 
    /**
     * base64字符串转化成图片
     * @param base64
     * @param fileName
     * @param filePath
     * @return
     * @throws Exception
     */
    public static File base64ToFile(String base64, String fileName, String filePath) throws Exception {
        if(base64.contains("data:image")){
            base64 = base64.substring(base64.indexOf(",")+1);
        }
        base64 = base64.replace("\r\n", "");
        //创建文件目录
        File file = File.createTempFile(base64, fileName, new File(filePath));
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes =  decoder.decodeBuffer(base64);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        }finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }
 
    /**
     * 图片转化成base64字符串
     * @param imgFile
     * @return
     */
    public static String GetImageStr(File imgFile) {//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
    }
 
}