JDK 8+ 原生支持,仅需两行代码:Files.readAllBytes() 读取图片字节数组,Base64.getEncoder().encodeToString() 编码为字符串;支持 jpg/png/gif 等格式,可扩展为带 MIME 的 Data URL,注意大图膨胀、中文路径和文件存在性。
直接用 java.util.Base64 和 java.nio.file.Files 两行代码就能搞定,不用额外依赖,JDK 8+ 原生支持。
核心逻辑:把图片文件转成字节数组 → 用 Base64 编码 → 转成字符串。推荐用 Files.readAllBytes() 简洁读取,避免流操作和异常手动处理(仍需 try-catch)。
示例代码:
import java.nio.file.*;
import java.util.Base64;
public class ImageToBase64 {
public static String imageToBase64(String imagePath) throws Exception {
byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
return Base64.getEncoder().encodeToString(imageBytes);
}
}
"src/main/resources/logo.png")data:image/png;base64,),如需用于 HTML img 标签,可手动拼接网页中直接显示常用 Base64 图片时,需要加上 data:[mime];base64,[data] 格式。可通过文件扩展名简单推断 MIME 类型。
示例方法:
public static String imageToDataUrl(String imagePath) throws Exception {
Path path = Paths.get(imagePath);
String mimeType = Files.probeContentType(path); // 尝试自动识别
if (mimeType == null) {
String ext = imagePath.substring(imagePath.lastIndexOf('.') + 1).toLowerCase();
mimeType = switch (ext) {
case "png" -> "image/png";
case "jpg", "jpeg" -> "image/jpeg";
case "gif" -> "image/gif";
default -> "image/octet-stream";
};
}
byte[] bytes = Files.readAllBytes(path);
String base64 = Base64.getEncoder().encodeToString(bytes);
return "data:" + mimeType + ";base
64," + base64;
}
Files.probeContentType() 在多数系统上能准确识别,但不保证 100% 可靠,所以加了 fallback 判断扩展名,浏览器原生支持Paths.get() 解析失败,建议用 URI 转换:Paths.get(new URI("file:///D:/测试/logo.png"))
Files.readAllBytes() 对不存在路径会抛 NoSuchFileException
基本上就这些。两行核心代码,加上一点健壮性处理,就能稳定跑在任意标准 Java 环境里。