JAVA 把base64图片数据转为本地图片

本文详细介绍了如何使用Java处理Base64编码的图像数据,并将其转换为本地磁盘上的图片文件,涵盖了编码解码过程和文件保存步骤。

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

    /**
         * 替换html中的base64图片数据为实际图片
         * @param html
         * @param fileRoot 本地路径
         * @param serRoot 服务器路径
         * @return
         */
        public static String replaceBase64Image(String html,String fileRoot,String serRoot){
            File file = new File(fileRoot);
            if(!file.exists()){//文件根目录不存在时创建
                new File(fileRoot).mkdirs();
            }
            String htmlContent = html;
            Pattern pattern = Pattern.compile("\\<img[^>]*src=\"data:image/[^>]*>");
            Matcher matcher = pattern.matcher(html);
            GUIDUtils.init();
            while(matcher.find()){      //找出base64图片元素
                String str = matcher.group();
                String src = ExStringUtils.substringBetween(str, "src=\"", "\"");//src="..."
                String ext = ExStringUtils.defaultIfEmpty(ExStringUtils.substringBetween(str, "data:image/", ";"), "jpg");//图片后缀
                String base64ImgData = ExStringUtils.substringBetween(str, "base64,", "\"");//图片数据
                if(ExStringUtils.isNotBlank(ext)&&ExStringUtils.isNotBlank(base64ImgData)){
                    //data:image/gif;base64,base64编码的gif图片数据
                    //data:image/png;base64,base64编码的png图片数据
                    if("jpeg".equalsIgnoreCase(ext)){//data:image/jpeg;base64,base64编码的jpeg图片数据
                        ext = "jpg";
                    } else if("x-icon".equalsIgnoreCase(ext)){//data:image/x-icon;base64,base64编码的icon图片数据
                        ext = "ico";
                    }
                    String fileName = GUIDUtils.buildMd5GUID(false)+"."+ext;//待存储的文件名
                    String filePath = fileRoot+File.separator+fileName;//图片路径
                    try {
                        convertBase64DataToImage(base64ImgData, filePath);//转成文件
                        String serPath = serRoot+fileName;//服务器地址
                        htmlContent = htmlContent.replace(src, serPath);//替换src为服务器地址
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return htmlContent;
        }
        /**
         * 把base64图片数据转为本地图片
         * @param base64ImgData
         * @param filePath
         * @throws IOException
         */
        public static void convertBase64DataToImage(String base64ImgData,String filePath) throws IOException {
            BASE64Decoder d = new BASE64Decoder();
            byte[] bs = d.decodeBuffer(base64ImgData);
            FileOutputStream os = new FileOutputStream(filePath);
            os.write(bs);
            os.close();
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值