base64文件编码解码

x33g5p2x  于2021-08-23 转载在 Java  
字(1.9k)|赞(0)|评价(0)|浏览(545)

一 前言

本篇文章只是在工作中用到了,知识追寻者随便记录一下,以备不时只须,有用你就用吧;

二 base编码

Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,可以使用64个可打印字符来表示二进制数据的方法;

更多参考

https://blog.csdn.net/qq_20545367/article/details/79538530

https://blog.csdn.net/wufaliang003/article/details/79573512

一般文件进行base64编码后都有个前缀声明为base64图片;比如图片的编码如下

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB3AAAAPP...........

真正的编码内容是data:image/png;base64,后的内容;

iVBORw0KGgoAAAANSUhEUgAAB3AAAAPP...........

三 base64文件编码解码

3.1 编码

编码后返回编码的字符串

/* *
     * @Author lsc
     * <p> base64编码 </p>
     * @Param [path]
     * @Return java.lang.String  返回编码后的字符串
     */
    public static String encodeBase64File(String path){
        // 读取文件
        File file = new File(path);
        // 声明输入流
        FileInputStream inputFile = null;
        // 声明字节数组
        byte[] buffer = null;
        try {
            inputFile = new FileInputStream(file);
            // 创建字节数组
            buffer = new byte[(int) file.length()];
            // 输入
            inputFile.read(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                inputFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 编码
        return new BASE64Encoder()
                .encode(buffer);
    }

也可以将字节数组放入输入流进行对象存储

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer);

3.2 解码

将编码后的字符串重新转为文件

/* *
     * @Author lsc
     * <p> base64解码 </p>
     * @Param [base64Code, targetPath] 将编码后的字符串解码为文件
     * @Return void
     */
    public static void decodeBase64File(String base64Code, String targetPath) {
        // 输出流
        FileOutputStream out =null;
        // 将base 64 转为字节数字
        byte[] buffer = new byte[0];
        try {
            buffer = new BASE64Decoder().decodeBuffer(base64Code);
            // 创建输出流
            out = new FileOutputStream(targetPath);
            // 输出
            out.write(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

3.3测试示例

	@Test
    public void test(){
        try {
            // 文件路径
            String filePath = "C:\\mydata\\generator\\世界地图.png";
            // 编码
            String encodeBase64File = encodeBase64File(filePath);
            // 剔除base64声明头
            String code = encodeBase64File.replace("data:image/png;base64,", "");
            //解码
            decodeBase64File(code,"C:\\mydata\\generator\\base64.png");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

四 base64在线转换工具

http://www.jsons.cn/img2base64/

https://base64.supfree.net/

相关文章

微信公众号

最新文章

更多