欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

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

来源: javaer 分享于  点击 19238 次 点评:132

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


目录
  • Java文件与Base64之间的转化
    • 1、文件转Base64工具类
    • 2、Base64转文件工具类
    • 3、综合案例
  • 总结

    Java文件与Base64之间的转化

    1、文件转Base64工具类

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

    /**
     * 文件转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格式的图片、视频下载到本地

    /**
     * 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、综合案例

    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<String, String>> fileToBase64() {
            List<Map<String, String>> 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<String, String>() {{
                    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<String, String>() {{
                    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<String, String>> dataList) {
            for (Map<String, String> 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<String, String>> dataList = fileToBase64();
            // Base64转文件
            base64ToFile(dataList);
        }
    }
    

    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持3672js教程。

    您可能感兴趣的文章:
    • 什么是Base64以及在Java中如何使用Base64编码
    • Java中图片转换为Base64的示例及注意事项
    • java的springboot实现将base64编码转换pdf
    • Java如何向Word模板中插入Base64图片和数据信息
    • java中Base64字符串出现不合法字符的问题解决
    相关栏目:

    用户点评