public static String convertImageToBase64(String url) throws IOException {
String urls = url.replaceAll("192.168.10.242", "192.192.192.192");
// 创建HTTP客户端
try (CloseableHttpClient httpClient = HttpClients.createDefault();
// 发送GET请求
CloseableHttpResponse response = httpClient.execute(new HttpGet(urls));
// 获取图片输入流
InputStream inputStream = response.getEntity().getContent()) {
// 验证响应状态
if (response.getStatusLine().getStatusCode() != 200) {
throw new IOException("获取图片失败,状态码: " + response.getStatusLine().getStatusCode());
}
// 读取图片字节
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 获取图片MIME类型
String contentType = response.getEntity().getContentType().getValue();
// 转换为Base64并添加数据头
return "data:" + contentType + ";base64," +
Base64.getEncoder().encodeToString(outputStream.toByteArray());
}
}
public static void main(String[] args) throws IOException {
System.out.println(convertImageToBase64("http://192.168.14.4:8803/1.png"));
}