【翻譯】影像到Base64字串轉換

六七十三發表於2022-12-24

1 概覽

在這個簡短的教程中,我們將介紹如何使用 Apache Common IO 包和 Java 8 原生類 Base64 將圖片檔案轉成 base64 字串,然後把 base64 字串再轉成圖片。

這個操作也可以應用到任何二進位制檔案或者二進位制陣列中。當我們需要以 json 格式傳輸二進位制內容的時候,例如從移動app程式傳到到 REST 端時,它非常有用。

2 Maven 依賴

新增一下依賴到 pom.xml 中:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

你可以在 maven 中央倉庫找到 commons-io 包的最新版本。Maven Central.

3 將圖片轉成 base64 字串

首先,我們將檔案內容轉成 byte 陣列,然後使用 Java 8 的 Base64 類編碼這個陣列。

byte[] fileContent = FileUtils.readFileToByteArray(new File(filePath));
String encodedString = Base64.getEncoder().encodeToString(fileContent);

encodeToString 欄位是 A-Za-z0-9+/ 集合中的字串,解碼器拒絕該集合之外的任何字元。

4 將 base64 字串轉成圖片

現在我們有一個 Base64 字串了,讓我們把它編碼回去成二進位制檔案並且寫入檔案。

byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
FileUtils.writeByteArrayToFile(new File(outputFileName), decodedBytes);

5 測試我們的程式碼

最後,我們可以透過讀取一個檔案,將其編碼為 Base64 字串,然後解碼回一個新檔案來驗證程式碼是否正確工作:

public class FileToBase64StringConversionUnitTest {

    private String inputFilePath = "test_image.jpg";
    private String outputFilePath = "test_image_copy.jpg";

    @Test
    public void fileToBase64StringConversion() throws IOException {
        // load file from /src/test/resources
        ClassLoader classLoader = getClass().getClassLoader();
        File inputFile = new File(classLoader
          .getResource(inputFilePath)
          .getFile());

        byte[] fileContent = FileUtils.readFileToByteArray(inputFile);
        String encodedString = Base64
          .getEncoder()
          .encodeToString(fileContent);

        // create output file
        File outputFile = new File(inputFile
          .getParentFile()
          .getAbsolutePath() + File.pathSeparator + outputFilePath);

        // decode the string and write to file
        byte[] decodedBytes = Base64
          .getDecoder()
          .decode(encodedString);
        FileUtils.writeByteArrayToFile(outputFile, decodedBytes);

        assertTrue(FileUtils.contentEquals(inputFile, outputFile));
    }
}

6 結論

這篇文章非常切題,它介紹了將任何檔案的內容編碼為 Base64 字串,並將Base64 字串解碼為位元組陣列,並使用 Apache Common IO 和 Java 8 特性將其儲存到檔案中。

原文地址:https://www.baeldung.com/java...

相關文章