1. 概要

このクイックチュートリアルでは、画像ファイルをBase64 String にエンコードし、それをデコードして、ApacheCommonIOとJava8のネイティブBase64機能を使用して元の画像を取得する方法について説明します。

この操作は、任意のバイナリファイルまたはバイナリ配列に適用できます。 モバイルアプリからRESTエンドポイントなど、JSON形式のバイナリコンテンツを転送する必要がある場合に便利です。

Base64変換の詳細については、こちらの記事をご覧ください。

2. Mavenの依存関係

次の依存関係をpom.xmlファイルに追加しましょう。

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

Apache Commons IOの最新バージョンは、 MavenCentralにあります。

3. 画像ファイルをBase64文字列に変換します

まず、ファイルの内容をバイト配列に読み取り、Java 8 Base64クラスを使用してエンコードします。

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

encodeStringA-Za-z0-9+ /のセット内の文字のStringであり、デコーダーはこのセット外の文字を拒否します。

4. Base64 Stringを画像ファイルに変換します

これでBase64String ができました。デコードしてバイナリコンテンツに戻し、新しいファイルに書き込みましょう。

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

5. コードのテスト

最後に、ファイルを読み取り、Base64 String にエンコードして、新しいファイルにデコードすることで、コードが正しく機能していることを確認できます。

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 String にエンコードし、Base64 String をバイト配列にデコードして、ApacheCommonを使用してファイルに保存する基本について説明します。 IOおよびJava8の機能。

いつものように、コードスニペットはGitHubにあります。