首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 8 Base64 編解碼圖片實戰:內嵌 HTML 展示

     編輯:Java 相關知識

JDK 8 新特性

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("解碼文件已生成");
    }
}

HTML 內嵌展示

<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)。

應用場景

  • 小圖標/頭像內嵌,減少 HTTP 請求
  • 郵件模板、離線頁面、CSS 背景圖
  • 注意:Base64 體積比原文件大 ~33%,不適合大圖

編解碼 API 速查

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
方法說明
Base64.getEncoder().encodeToString(byte[])字節數組 → 字符串
Base64.getEncoder().encode(byte[])字節數組 → 字節數組
Base64.getDecoder().decode(String)字符串 → 字節數組
Base64.getDecoder().decode(byte[])字節數組 → 字節數組