图片Base64编码与解码

本文介绍了如何将图片文件转换为Base64编码,包括直接转换文件和通过文件路径的方式。同时,也讨论了如何将Base64编码还原为图片。作者分享了相关代码实现,并提醒了版权注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将图片文件进行base64编码
以下为两种方式,一直是直接将文件格式的转为base64,另一种则是以路径作为参数:

public void changeBase(MultipartFile file1,String path){
    FileInputStream stream =null;
    StringBuffer encode1 =new StringBuffer();
    StringBuffer encode2 =new StringBuffer();
    File file2 = new File(path);
    try {
     /*方法1:前端直接传文件*/
        encode1 .append( Base64.getEncoder().encodeToString(file1.getBytes()));
        //获取文件格式
        String type = file1.getContentType();
        //用于说明文件格式(可要可不要)
        encode1.append("data:").append(type).append(";base64,");
     /*方法2:前端传文件路径*/
        //将文件转为流
        stream = new FileInputStream(file2);
        //新建一个用来存储文件二进制的数据
        byte[] bytes = new byte[(int) file2.length()];
        stream.read(bytes);
        encode2 .append( Base64.getEncoder().encodeToString(bytes));

    } catch (IOException e) {
        e.printStackTrace();
    }
}

将base64编码后的参数转为图片

public  void changePic(String s) {
        //定义一个正则表达式的筛选规则,为了获取图片的类型
        String rgex = "data:image/(.*?);base64";
        //获取编码后文件格式
        String type = getSubUtilSimple(s, rgex);
        if (StringUtils.isEmpty(type)){
            type="jpeg";
        }
        //去除base64图片的前缀
        s = s.replaceFirst("data:(.+?);base64,", "");
        byte[] b;
        byte[] bs;
        OutputStream os = null;
        String fileName = "";
        //把图片转换成二进制
        b = cn.hutool.core.codec.Base64.decode(s.replaceAll(" ", "+"));
        //生成路径
        String path = "d:/";
        //随机生成图片的名字,同时根据类型结尾
        fileName = UUID.randomUUID().toString() + "." + type;
        File file = new File(path);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        File imageFile =new File(path + "/" + fileName);
        BASE64Decoder d = new BASE64Decoder();
        // 保存
        try {
            bs = d.decodeBuffer(cn.hutool.core.codec.Base64.encode(b));
            os = new FileOutputStream(imageFile);
            os.write(bs);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.getLocalizedMessage();
                }
            }
        }
    }

    public  String getSubUtilSimple(String soap,String rgex){
        //生成正则函数
        Pattern pattern = Pattern.compile(rgex);
        Matcher m = pattern.matcher(soap);
        while(m.find()){
            return m.group(1);
        }
        return "";
    }

作者:那就省略号吧
链接:https://www.jianshu.com/p/11ec024f7337
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值