在 Java 中使用 Hutool 工具庫將圖片轉換為 Base64 字符串非常簡單。Hutool 提供了 Base64FileUtil 等工具類,可以輕鬆完成這個任務。

示例代碼:

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;

import java.io.File;

public class ImageToBase64 {
    public static void main(String[] args) {
        // 圖片文件路徑
        String imagePath = "path/to/your/image.jpg";

        // 讀取圖片為字節數組
        byte[] imageBytes = FileUtil.readBytes(imagePath);

        // 將字節數組轉為 Base64 字符串(不帶 data:image/... 前綴)
        String base64Str = Base64.encode(imageBytes);

        // 如果需要用於 HTML 或 CSS 中,通常加上前綴,例如:
        String mimeType = "image/jpeg"; // 根據實際格式調整,如 image/png
        String base64WithPrefix = "data:" + mimeType + ";base64," + base64Str;

        System.out.println(base64WithPrefix);
    }
}

説明:

  • FileUtil.readBytes():讀取整個文件為 byte[]
  • Base64.encode():將字節數組編碼為 Base64 字符串。
  • MIME 類型需根據圖片格式設置,常見類型有:
  • .jpg / .jpegimage/jpeg
  • .pngimage/png
  • .gifimage/gif
  • .webpimage/webp

Maven 依賴(確保已引入 Hutool):

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.22</version> <!-- 請使用最新版本 -->
</dependency>

✅ 提示:如果你是從 InputStream、網絡 URL 或字節數組讀取圖片,也可以先轉成 byte[] 再用 Base64.encode()

hutool 將圖片轉為base64 字符_java