Convert Image byte[] Array to Base64 encoded String in Java

In this tutorial, you will learn how to convert an image byte[] array into a Base64 encoded string of characters.

Additionally, you might be interested in checking the “Converting byte[] Array to String in Java” tutorial.

Convert Image to a byte[] Array

Let’s assume that we have an image on our computer. Our task is to first convert this image into a byte[] array. Since the image is just a file, we can use the Files class in Java to read image bytes into an array.

byte[] bytes = Files.readAllBytes(pathToImage);

Convert byte[] to a Base64 Encoded String

Once you have an array of bytes, you can easily convert it into a Base64 encoded string. To do that, you can use the Base64 class from java.util package.

String base64EncodedImageBytes = Base64.getEncoder().encodeToString(bytes);

Decode Base64 String into byte[]

Eventually, you will need to decode the Base64 encoded string of characters back into a byte[]. To do that you will use the Base64.getDecoder().decode() method.

byte[] decode = Base64.getDecoder().decode(base64EncodedString);

Let’s have a look at a complete code example.

Convert Image to a Base64 Encoded String

Below is a complete code example that demonstrates how to read image bytes into an array of bytes and then convert this array of bytes into a Base64 encoded string.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class App {
    public static void main(String[] args) {

        String imageFilePath = "/Users/sergeykargopolov/Downloads/Design_2-01.png";
        Path pathToImage = Paths.get(imageFilePath);

        if (Files.notExists(pathToImage)) {
            throw new IllegalArgumentException("Image does not exist at the specified path");
        }

        try {

            // 1. Convert image to an array of bytes
            byte[] imageBytes = Files.readAllBytes(pathToImage);

            // 2. Encode image bytes[] to Base64 encoded String
            String base64EncodedImageBytes = Base64.getEncoder().encodeToString(imageBytes);
            System.out.println(base64EncodedImageBytes);

           // 3. Decode Base64 encoded String back to a byte[] array
           byte[] decodedImageBytes = Base64.getDecoder().decode(base64EncodedImageBytes);


        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

I hope this very short blog post was helpful to you.

There are many other useful tutorials you can find on this site. To find Java-related tutorials, check out the Java tutorials page.

Happy learning!