Help Center/ Optical Character Recognition/ FAQs/ API/ How Do I Obtain the Base64 Encoding of an Image?
Updated on 2025-10-23 GMT+08:00

How Do I Obtain the Base64 Encoding of an Image?

The input image parameter of OCR is the Base64 encoding of the image. This section describes how to convert a local image to a Base64 encoding. You can also use an online conversion tool.

Python example:

Replace d:\demo.jpg in the code with the actual image path.

import base64
with open("d:/demo.jpg", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read()).decode()
print(encoded_string)

Ensure that the file path d:/demo.jpg is accurate and that the file exists in the path when executing the code. In certain Windows environments, the default character encoding settings may not be compatible with the code, leading to decoding errors upon reading. If this occurs, you can change decode() in the code to decode('utf-8') to align with the correct character encoding.

Figure 1 Example

Java example:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

public class ImageToBase64 {
    public static void main(String[] args) {
        String imagePath = "d:/demo.jpg";
        String base64String = encodeImageToBase64(imagePath);
        if (base64String != null) {
            System.out.println(base64String);
        }
    }

    private static String encodeImageToBase64(String imagePath) {
        File file = new File(imagePath);
        try (FileInputStream imageInFile = new FileInputStream(file)) {
            // Read the image file into the byte array.
            byte[] imageData = new byte[(int) file.length()];
            imageInFile.read(imageData);

            // Encode the image into a Base64 string.
            return Base64.getEncoder().encodeToString(imageData);
        } catch (IOException e) {
            System.err.println("An error occurred while processing the image: " + e.getMessage());
            return null;
        }
    }
}
Figure 2 Example