代码如下:
public static void main(String[] args) throws ParseException, IOException, URISyntaxException {
String base64 = imageToBase64("https://images.cnblogs.com/cnblogs_com/qq1445496485/1909145/o_201230130836%E5%9B%9B%E5%A8%83.jpg");
System.out.println(base64);
base64ToImage(base64, "D:\\123.jpg");
}
private static String imageToBase64(String imageUrl) throws IOException, URISyntaxException {
// 从 URL 读取图片
URL url = new URL(imageUrl);
// Files.createTempFile 创建一个临时文件
Path tempFile = Files.createTempFile("tempImage", ".jpg");
// Files.copy 将远程图片下载到这个临时文件中
Files.copy(url.openStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);
byte[] imageBytes = Files.readAllBytes(tempFile);
// 删除临时文件
System.out.println("==============:" + tempFile.toAbsolutePath());
File file = tempFile.toAbsolutePath().toFile();
file.delete();
// 将图片字节数组编码为 Base64 字符串
return Base64.getEncoder().encodeToString(imageBytes);
}
private static void base64ToImage(String base64Image, String outputPath) throws IOException {
// 解码 Base64 字符串为图片字节数组
byte[] imageBytes = Base64.getDecoder().decode(base64Image);
// 将图片字节数组写入文件
Files.write(Paths.get(outputPath), imageBytes); // 修改这里
}