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;
|
}
|
|
}
|
|
}
|