I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we’re going to cover how to encode image file to a Base64 String, then decode it to retrieve the original image using Apache Common IO and Java 8 native Base64 features.

This operation could be applied for any binary files or binary arrays. It’s useful when we need to transfer binary content in JSON format such as from mobile app to REST endpoint.

For more information about Base64 conversion, check out this article here.

2. Maven Dependency

Let’s add the following dependencies to the pom.xml file:

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

You can find the latest version of Apache Commons IO on Maven Central.

3. Convert Image File to Base64 String

First of all, let’s read the file content to a byte array and use Java 8 Base64 class to encode it:

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

The encodedString is a String of characters in the set of A-Za-z0-9+/, and the decoder rejects any characters outside of this set.

4. Convert Base64 String to Image File

Now we have a Base64 String, let’s decode it back to binary content and write to a new file:

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

5. Testing Our Code

Finally, we can verify that the code is working correctly by reading a file, encoding it to a Base64 String, and decoding it back to a new file:

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. Conclusion

This to-the-point article explains the basic of encoding any file’s content to a Base64 String, and decoding a Base64 String to a byte array and save it to a file using Apache Common IO and Java 8 features.

As always, code snippets can be found over on GitHub.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS