Convert image to base64 string in Java

Here I will show you how to convert an image to base64 string in Java.

In programming, Base64 is a set of binary-to-text encoding schemes that represent binary data in an ASCII string format. This is the Standard definition of Base64. Base64 is commonly used when we want to encode binary data which will then be transferred to some other media.

Suppose we want to get or send some image or database to the server, in this case, we can simply convert the image to base64. In Java, there is a built-in function for encoding an image to base64 and decoding it again at the other end which is available in binary class. The File is a class that is used to work with other files. Now, these files can be read by FileReader class.

Algorithm:

  1. Save the image location in a variable that has a File data type.
  2. Convert it to the String.

Import Packages

import java.io.File;
import java.io.FileInputStream;

Base64 can be found in the built-in package

import org.apache.commons.codec.binary.Base64;

After importing, create a class and then the main method. In the main method store the location of the image in the variable of the class File.

FileInputStream class reads byte-oriented data from an image or audio file. By creating a byte array of that file and reading the byte of data from the input stream with the help of read() method from FileInputStream class, we can convert it to the Base64.

public class Base64Converter{
    public static void main(String[] args){
        File f = new File("Image Location");
        FileInputStream fin = new FileInputStream(f);
        byte imagebytearray[] = new byte[(int)f.length()];
        fin.read(imagebytearray);
        String imagetobase64 = Base64.encodeBase64String(imagebytearray);
        fin.close();
    }
}

As you can see in the above example, there is a direct method for converting from image to base64 which is present in the Base64 class.

That’s all for this tutorial.

Also read: Rotate an Image in Java

Leave a Reply

Your email address will not be published.