Spring Boot 图片url转换为base64字符串

通过图片链接将图片转换为base64编码字符串

之前直接向前端传图片文件,遇到跨域问题,一直没有解决,干脆将图片的base64字符串给前端了
参数:String类型,imgurl 图片链接
返回值:String类型,编码后的字符串

    /**
     * 请求图片地址, 返回的结果进行base64编码
     * @param imgUrl 图片地址
     * @return
     */
    public static String requestUrlToBase64(String imgUrl) {
        String result = null;
        HttpURLConnection connection = null;

        try {
            URL url = new URL(imgUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            // 获取请求输入流
            InputStream inputStream = connection.getInputStream();
            // inputStream流数据转ByteArrayOutputStream
            int len = -1;
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }

            // ByteArrayOutputStream编码成base64字符串
            result = new String(Base64.getEncoder().encode(out.toByteArray()));
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(connection != null){
                connection.disconnect();
            }
        }

        return result;
    }

可以结合一些在线的图片转换工具进行测试
例如:http://tool.chinaz.com/tools/imgtobase
在这里插入图片描述

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个用于创建独立的、基于生产级别的Java应用程序的框架。它简化了Java开发过程,提供了快速开发和易于配置的特性。 Base64是一种将二进制数据编码成ASCII字符的编码方式。在Spring Boot中,可以使用Base64图片数据转换字符串,或者将字符串转换图片数据。 要将Base64字符串转换图片,可以按照以下步骤进行操作: 1. 将Base64字符串解码为字节数组。 2. 使用Java的ImageIO类将字节数组转换为BufferedImage对象。 3. 将BufferedImage对象保存为图片文件。 以下是一个示例代码,演示了如何在Spring Boot中将Base64字符串转换图片: ```java import java.io.*; import java.util.Base64; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; public class Base64ToImageConverter { public static void main(String[] args) { String base64String = "your_base64_string_here"; try { // 解码Base64字符串为字节数组 byte[] imageBytes = Base64.getDecoder().decode(base64String); // 将字节数组转换为BufferedImage对象 ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes); BufferedImage image = ImageIO.read(bis); // 保存BufferedImage对象为图片文件 File outputFile = new File("output_image.jpg"); ImageIO.write(image, "jpg", outputFile); System.out.println("图片保存成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 请注意,上述代码中的"your_base64_string_here"需要替换为实际的Base64字符串。另外,需要确保在运行代码时,存在可写入的目录以保存图片文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值