java.util.Base64 提供標準編碼器/解碼器,無需第三方庫。
public class Base64ImageConverter {
public static void main(String[] args) throws IOException {
Path imgPath = Paths.get("D:/temp/mm.png");
byte[] bytes = Files.readAllBytes(imgPath);
// 編碼
String base64 = Base64.getEncoder().encodeToString(bytes);
System.out.println("Base64 長度:" + base64.length());
// 解碼驗證
byte[] decoded = Base64.getDecoder().decode(base64);
Files.write(Paths.get("D:/temp/mm2.png"), decoded);
System.out.println("解碼文件已生成");
}
}
<div id="avatar" style="
width:128px; height:128px; border-radius:50%;
background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...') center/cover;
border:8px solid #EDEDED;"></div>
關鍵前綴:data:image/png;base64,(jpg 用 jpeg,gif 用 gif)。
| 方法 | 說明 |
|---|---|
| Base64.getEncoder().encodeToString(byte[]) | 字節數組 → 字符串 |
| Base64.getEncoder().encode(byte[]) | 字節數組 → 字節數組 |
| Base64.getDecoder().decode(String) | 字符串 → 字節數組 |
| Base64.getDecoder().decode(byte[]) | 字節數組 → 字節數組 |