Java program to convert an image to Base64 in 2 different ways

Java program to convert an image to Base64:

In this post, we will learn how to convert an image to Base64 string in Java. It is a binary-to-text encoding scheme. Base64 is used to transfer binary data in text format. For example, it is widely used in sending email attachments and sending files to the server.

In Java, it is pretty easy to convert an image to Base64 string by using its inbuilt classes.

The java.util.Base64 class provides a method to convert a byte array to Base64 string:

public String encodeToString(byte[] src)

We can convert an image to a byte array and use this method to encode it to a Base64 string. The conversion of file to byte can be different. Let me show you two ways to solve this program.

Method 1: By using javax.imageio.ImageIO:

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.File;
import java.util.Base64;

public class Main {
    public static void main(String[] args) {
        File imageFile = new File("givenImage.png");
        try {
            BufferedImage bufferedImage = ImageIO.read(imageFile);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
            byte[] fileByteArray = byteArrayOutputStream.toByteArray();

            String encodedStr = Base64.getEncoder().encodeToString(fileByteArray);
            System.out.println("Base64 String: " + encodedStr);

        } catch (IOException e) {
            // handle exception
        }
    }
}

In this method,

  • We are using javax.imageio.ImageIO to read the file and create a BufferedImage object.
  • It then write the output to a ByteArrayOutputStream object.
  • The toByteArray() method of the ByteArrayOutputStream returns a byte array holding the content of the image.
  • We can use the encodeToString method to get the encoded string.

If you run this program, it will print the encoded base64 string.

Method 2: By using java.nio.file.Files:

import java.io.IOException;
import java.nio.file.Files;
import java.io.File;
import java.util.Base64;

public class Main {
    public static void main(String[] args) {
        File imageFile = new File("givenImage.png");
        try {
            byte[] fileByteArray = Files.readAllBytes(imageFile.toPath());
            String encodedStr = Base64.getEncoder().encodeToString(fileByteArray);
            System.out.println("Base64 String: " + encodedStr);
        } catch (IOException e) {
            // handle exception
        }
    }
}
  • The java.nio.file.Files class provides a static method to read all bytes of an image.
  • It is passed to the encodeToString method to get the encoded base64 string.

If you run this example with the same image, it will print the same output.

You might also like: