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