JDK 8+ 原生支持,仅需两行代码:Files.readAllBytes() 读取图片字节数组,Base64.getEncoder().encodeToString() 编码为字符串;支持 jpg/png/gif 等格式,可扩展为带 MIME 的 Data URL,注意大图膨胀、中文路径和文件存在性。

直接用 java.util.Base64 和 java.nio.file.Files 两行代码就能搞定,不用额外依赖,JDK 8+ 原生支持。
读取图片文件并编码为 Base64 字符串
核心逻辑:把图片文件转成字节数组 → 用 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);
}
}
- 支持常见格式:jpg、png、gif 等,只要文件是有效二进制图片即可
- 注意路径:传入绝对路径或相对于运行目录的相对路径(如
"src/main/resources/logo.png") - 编码结果不含前缀(如
data:image/png;base64,),如需用于 HTML img 标签,可手动拼接
带 MIME 类型的完整 Data URL(实用增强版)
网页中直接显示常用 Base64 图片时,需要加上 data:[mime];base64,[data] 格式。可通过文件扩展名简单推断 MIME 类型。
立即学习“Java免费学习笔记(深入)”;
示例方法:
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 + ";base64," + base64;
}
-
Files.probeContentType()在多数系统上能准确识别,但不保证 100% 可靠,所以加了 fallback 判断扩展名 - 返回值可直接赋给 HTML 的
,浏览器原生支持
注意事项与避坑点
- 大图慎用:Base64 编码后体积比原图增大约 33%,几 MB 的图片会导致字符串过长,影响内存和传输效率
- 中文路径问题:Windows 下若路径含中文且未正确配置,默认字符集可能导致
Paths.get()解析失败,建议用 URI 转换:Paths.get(new URI("file:///D:/测试/logo.png")) - 空指针风险:确保文件存在且可读,
Files.readAllBytes()对不存在路径会抛NoSuchFileException - 不需要 Apache Commons 或 Guava —— JDK 自带方案足够轻量可靠
基本上就这些。两行核心代码,加上一点健壮性处理,就能稳定跑在任意标准 Java 环境里。










