文件与base64位相互转换

1.图片转base64字符串

     //图片文件转base64位字符
    public static void main(String[] args) throws IOException {
        //源文件的磁盘地址
        String picPath = "C:\\Users\\ckj\\Desktop\\png\\wyz.jpg";
        //base64位保存的地址
        String txtPath = "C:\\Users\\ckj\\Desktop\\png\\base64.txt";
        BufferedInputStream bf = null;
        BufferedOutputStream bo = null;
        try {
            //使用字节缓冲流读取图片文件数据
            bf = new BufferedInputStream(new FileInputStream(picPath));
            //获取图片文件大小
            int available = bf.available();
            //基于图片文件大小,创建缓冲大小
            byte[] buff = new byte[available];
            //读取整个文件
            bf.read(buff);
            BASE64Encoder base64 = new BASE64Encoder();
            //对文件进行base64编码
            String encode = base64.encode(buff);
            //字节缓冲输出流
            bo = new BufferedOutputStream(new FileOutputStream(txtPath));
            //输出到外部
            bo.write(encode.getBytes());
        } catch (Exception e) {
            throw e;
        } finally {
            //后面创建的流 应该在前面先关闭
            if (bo != null) {
                bo.close();
            }
            if (bf != null) {
                bf.close();
            }
        }
    }

2.base64字符串转图片(不仅仅是文件,理论上全部东西都可以转,音频,视频,word等等)

  public static void main(String[] args) throws IOException {
        //文件的磁盘地址
        String picPath = "C:\\Users\\ckj\\Desktop\\png\\wyz2.jpg";
        //base64位保存的地址
        String txtPath = "C:\\Users\\ckj\\Desktop\\png\\base64.txt";
        BufferedInputStream bi = null;
        BufferedOutputStream bo = null;
        try {
            //使用字节缓冲流读取文件数据
            bi = new BufferedInputStream(new FileInputStream(txtPath));
            //获取文件大小
            int available = bi.available();
            //基于文件大小,创建缓冲大小
            byte[] buff = new byte[available];
            //读取整个文件
            bi.read(buff);
            BASE64Decoder base64Decoder = new BASE64Decoder();
            //对文件进行base64编码 转码
            byte[] bytes = base64Decoder.decodeBuffer(new String(buff));
            //字节缓冲输出流
            bo = new BufferedOutputStream(new FileOutputStream(picPath));
            bo.write(bytes);
        } catch (Exception e) {
            throw e;
        } finally {
            //后面创建的流 应该在前面先关闭
            if (bo != null) {
                bo.close();
            }
            if (bi != null) {
                bi.close();
            }
        }
    }

3.base64字符串直接变图片

找到我们刚刚转换出来的txt文件,如果是图片,在这个txt前面加上

data:image/jpeg;base64,

注意有逗号!!!
在这里插入图片描述
转后
在这里插入图片描述
直接全选复制,丢到浏览器的请求地址栏即可,注意!!不是丢到百度搜索!!
丢这里
在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值