Java实现图片转base64字符串和图片互相转换(适用于网络图片)

代码如下:

	public static void main(String[] args) throws ParseException, IOException, URISyntaxException {
        String base64 = imageToBase64("https://images.cnblogs.com/cnblogs_com/qq1445496485/1909145/o_201230130836%E5%9B%9B%E5%A8%83.jpg");
        System.out.println(base64);
        base64ToImage(base64,  "D:\\123.jpg");

    }

    private static String imageToBase64(String imageUrl) throws IOException, URISyntaxException {
        // 从 URL 读取图片
        URL url = new URL(imageUrl);
        // Files.createTempFile 创建一个临时文件
        Path tempFile = Files.createTempFile("tempImage", ".jpg");
        // Files.copy 将远程图片下载到这个临时文件中
        Files.copy(url.openStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);
        byte[] imageBytes = Files.readAllBytes(tempFile);

        // 删除临时文件
        System.out.println("==============:" + tempFile.toAbsolutePath());
        File file = tempFile.toAbsolutePath().toFile();
        file.delete();
        
        // 将图片字节数组编码为 Base64 字符串
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    private static void base64ToImage(String base64Image, String outputPath) throws IOException {
        // 解码 Base64 字符串为图片字节数组
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);

        // 将图片字节数组写入文件
        Files.write(Paths.get(outputPath), imageBytes);  // 修改这里
    }
  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值