wenminjie
2026-07-13 3e5c432f8e61c23d45f369e33e03aef5dd850d4b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.ruoyi.web.controller.tool;
 
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
 
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
@Slf4j
@Component
public class ImageUtil {
 
    /**
     * 将网络图片URL转为Base64编码
     *
     * @param imageUrl 网络图片地址
     * @return Base64编码的图片字符串
     */
    public static String imageUrlToBase64(String imageUrl) {
        if (StringUtils.isEmpty(imageUrl)) {
            return null;
        }
 
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
 
        try {
            // 1. 创建URL连接
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(10000);
            connection.setDoInput(true);
 
            // 2. 获取图片数据
            inputStream = connection.getInputStream();
            outputStream = new ByteArrayOutputStream();
 
            byte[] buffer = new byte[8192];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
 
            // 3. 转换为Base64
            byte[] imageBytes = outputStream.toByteArray();
            String base64 = Base64.encodeBase64String(imageBytes);
 
            // 4. 根据图片类型添加前缀
            String contentType = connection.getContentType();
            if (contentType != null && contentType.startsWith("image/")) {
                return "data:" + contentType + ";base64," + base64;
            }
 
            return "data:image/jpeg;base64," + base64;
 
        } catch (Exception e) {
            log.error("图片转Base64失败,URL:{}", imageUrl, e);
            return null;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception e) {
                log.error("关闭流失败", e);
            }
        }
    }
}