Java文件与Base64之间的转化方式

Java文件与Base64之间的转化

1、文件转Base64工具类

可以将图片、视频转化为Base64格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * 文件转Base64
 * @param filePath
 * @return
 */
public static String convertFileToBase64(String filePath) {
    try {
        // 读取文件为字节数组
        byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
 
        // 将字节数组转换为Base64编码的字符串
        String base64EncodedString = Base64.getEncoder().encodeToString(fileBytes);
 
        return base64EncodedString;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

2、Base64转文件工具类

将Base64格式的图片、视频下载到本地

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
/**
 * Base64转文件
 * @param base64String Base64字符串
 * @param filePath 输出的文件路径
 * @param mimeType
 *  MIME类型:
 *      视频 video/mp4
 *      PNG: image/png
 *      JPEG: image/jpeg
 *      GIF: image/gif
 *      BMP: image/bmp
 *      WebP: image/webp
 * @return
 */
public static boolean convertBase64ToFile(String base64String, String filePath, String mimeType) {
    try {
        // 将Base64编码的字符串转换为字节数组
        byte[] fileBytes = Base64.getDecoder().decode(base64String);
        // 创建文件头信息
        String header = "data:" + mimeType + ";base64,";
        byte[] headerBytes = header.getBytes();
        // 合并文件头和文件内容
        byte[] combinedBytes = new byte[headerBytes.length + fileBytes.length];
        System.arraycopy(headerBytes, 0, combinedBytes, 0, headerBytes.length);
        System.arraycopy(fileBytes, 0, combinedBytes, headerBytes.length, fileBytes.length);
        // 将字节数组写入文件
        Files.write(Paths.get(filePath), fileBytes);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

3、综合案例

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
package org.ming;
 
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
 
public class FileToBase64Converter {
    /**
     * 文件转Base64
     * @param filePath
     * @return
     */
    public static String convertFileToBase64(String filePath) {
        try {
            // 读取文件为字节数组
            byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
 
            // 将字节数组转换为Base64编码的字符串
            String base64EncodedString = Base64.getEncoder().encodeToString(fileBytes);
 
            return base64EncodedString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 文件转Base64流程
     */
    public static List<map>> fileToBase64() {
        List<map>> dataList = new ArrayList();
        // 读取的图片路径
        String filePath = "D:\repo\java_base_test\static\img\GcJcSbJkBjVo.png";
        // 读取的视频路径
        String videoPath = "D:\repo\java_base_test\static\video\cs.mp4";
 
        String fileToBase64 = convertFileToBase64(filePath);
        String videoToBase64 = convertFileToBase64(videoPath);
 
        if (fileToBase64 != null) {
            System.out.println("图片转换成功");
            dataList.add(new HashMap() {{
                put("outPath", String.format("D:\repo\java_base_test\static\img\GcJcSbJkBjVo_%s.png", new Date().getTime()));
                put("base64Str", fileToBase64);
                put("mimeType", "image/png");
            }});
        } else {
            System.out.println("图片转换失败");
        }
 
        if (videoToBase64 != null) {
            System.out.println("视频转换成功");
            dataList.add(new HashMap() {{
                put("outPath", String.format("D:\repo\java_base_test\static\video\cs_%s.mp4", new Date().getTime()));
                put("base64Str", videoToBase64);
                put("mimeType", "video/mp4");
            }});
        } else {
            System.out.println("视频转换失败");
        }
 
        return dataList;
    }
 
    /**
     * Base64转文件
     * @param base64String Base64字符串
     * @param filePath 输出的文件路径
     * @param mimeType
     *  MIME类型:
     *      视频 video/mp4
     *      PNG: image/png
     *      JPEG: image/jpeg
     *      GIF: image/gif
     *      BMP: image/bmp
     *      WebP: image/webp
     * @return
     */
    public static boolean convertBase64ToFile(String base64String, String filePath, String mimeType) {
        try {
            // 将Base64编码的字符串转换为字节数组
            byte[] fileBytes = Base64.getDecoder().decode(base64String);
            // 创建文件头信息
            String header = "data:" + mimeType + ";base64,";
            byte[] headerBytes = header.getBytes();
            // 合并文件头和文件内容
            byte[] combinedBytes = new byte[headerBytes.length + fileBytes.length];
            System.arraycopy(headerBytes, 0, combinedBytes, 0, headerBytes.length);
            System.arraycopy(fileBytes, 0, combinedBytes, headerBytes.length, fileBytes.length);
            // 将字节数组写入文件
            Files.write(Paths.get(filePath), fileBytes);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * base64转文件流程
     * @param base64String
     * @param filePath
     */
    public static void base64ToFile(List<map>> dataList) {
        for (Map resMap : dataList) {
            boolean flag = convertBase64ToFile(resMap.get("base64Str"), resMap.get("outPath"), resMap.get("mimeType"));
            if (flag) {
                System.out.println(resMap.get("outPath") + " 转化成功");
            } else {
                System.out.println(resMap.get("outPath") + " 转化失败");
            }
        }
    }
 
    public static void main(String[] args) {
        // 文件转Base64
        List<map>> dataList = fileToBase64();
        // Base64转文件
        base64ToFile(dataList);
    }
}
</map></map></map></map>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/java/14695.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部