双重预防项目-国泰新华二开定制版
heheng
2025-06-19 46c37398a52d1dcf81788960ec90faa91249e77f
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
package com.ruoyi.common.utils;
 
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
 
public class ImageToBase64 {
 
    public static String convertImageToBase64(String imageUrl) {
        try {
            // 创建URL对象
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 
            // 设置请求方法和超时时间
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setDoInput(true);
 
            // 获取输入流
            InputStream inputStream = connection.getInputStream();
 
            // 读取图片字节数据
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            byte[] imageBytes = byteArrayOutputStream.toByteArray();
 
            // 关闭流
            inputStream.close();
            byteArrayOutputStream.close();
 
            // 将图片字节数组编码为 Base64 字符串
            return Base64.getEncoder().encodeToString(imageBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
 
    }
 
}