How Do You Convert an Image to Base64 Using Java

Jan 15, 2024

1 min read

Published in

Here’s a simple Java code snippet to convert an image to Base64:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.io.File;
import java.io.FileInputStream;
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 ImageToBase64Converter {

    public static void main(String[] args) {
        try {
            String imagePath = "path/to/your/image.jpg";
            String base64String = convertImageToBase64(imagePath);
            System.out.println("Base64 String: " + base64String);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String convertImageToBase64(String imagePath) throws IOException {
        File imageFile = new File(imagePath);
        if (imageFile.exists()) {
            FileInputStream fileInputStream = new FileInputStream(imageFile);
            byte[] imageData = new byte[(int) imageFile.length()];
            fileInputStream.read(imageData);
            fileInputStream.close();
            return Base64.getEncoder().encodeToString(imageData);
        } else {
            throw new IOException("Image file not found: " + imagePath);
        }
    }
}

Replace "path/to/your/image.jpg" with the actual path to your image file. This code reads the image file, converts it to a byte array, and then encodes the byte array into a Base64 string.

Sharing is caring!