Java将网络图片转成输入流以及将url转成InputStream问题

将网络图片转成输入流以及将url转成InputStream

private static InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            log.info("获取网络图片出现异常,图片路径为:" + url);
            e.printStackTrace();
        }
        return null;
    }

Java将图片转成Base64

在日常的开发中,图片展示是一个经常见的开发任务,而图片展示也有好多种方式。

但也有一种是通过转成Base64编码来完成。

下面就是通过流转成Base64编码的主要代码。

try (InputStream in = null;
     ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            //建一个空的字节数组
            byte[] result = null;
              in=.........(获取你的图片的输入流)
            byte[] buf = new byte[1024];
            //用来定义一个准备接收图片总长度的局部变量
            int len;
            //将流的内容读取到buf内存中
            while ((len = in.read(buf)) > 0) {
                //将buf内存中的内容从0开始到总长度输出出去
                out.write(buf, 0, len);
            }
            //将out中的流内容拷贝到一开始定义的字节数组中
            result = out.toByteArray();
            //通过util包中的Base64类对字节数组进行base64编码
            String base64 = Base64.getEncoder().encodeToString(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

以上就是Java转成Base64的主要逻辑代码,剩下的就是将这段逻辑套入到你自己的代码里面。

注:如果需要返回到前端展示则需要加上一个前缀:

String code = "data:Image/" + "你的图片格式(例如:JPG/PNG)等等" + ";base64," + base64;

如果前端需要展示图片,就将code返回给前端。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文地址:https://blog.csdn.net/wenxingchen/article/details/126269707