当前位置: 代码网 > it编程>编程语言>Java > Java文件与Base64之间的转化方式

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

2025年02月12日 Java 我要评论
java文件与base64之间的转化1、文件转base64工具类可以将图片、视频转化为base64格式/** * 文件转base64 * @param filepath * @return */pub

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);
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com