【Java开发】之网络图片转Base64

1、引入依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

2、获取图片并转Base64

@Test
    void Test() throws IOException {

        // 获取图片流
        HttpGet httpGet = new HttpGet("图片url");
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();

        // 从流中获取数据
        byte[] data = new byte[(int) entity.getContentLength()];
        int offset = 0;
        int readBytes = 0;
        do {
            readBytes = inputStream.read(data, offset, 2048);
            offset += readBytes;
        } while (readBytes != -1);

        // Base64 编码
        Base64.Encoder encoder = Base64.getEncoder();
        String result = encoder.encodeToString(data);
        System.out.println(result);

        // 关闭资源
        response.close();
        httpClient.close();
    }

3、前端显示Base64图片

<!DOCTYPE html>
<html>
<head>
    <title>Image</title>
</head>
<body>
    <img src="data:image/png;base64, 将base64编码数据放在这里 ">
</body>
</html>

版权声明:本文为aiwangtingyun原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。