Java Convert BufferedImage to Byte Array

Tags: BufferedImage Byte Array

In this Java tutorial we learn how to convert a BufferedImage object to a byte[] array in Java programming language.

How to convert BufferedImage to byte[] array in Java

In Java to convert a BufferedImage to byte[] array we can firstly use the ImageIO.write() method to write the the BufferedImage object ByteArrayOutputStream and then get byte[] array from the ByteArrayOutputStream object.

String imageFilePath = "D:\\SimpleSolution\\qrcode.png";
File imageFile = new File(imageFilePath);
BufferedImage bufferedImage = ImageIO.read(imageFile);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
byte[] bytesOfImage = byteArrayOutputStream.toByteArray();

The following Java example code to show you how to read image file to BufferedImage object and convert it to byte[] array, from that byte[] array we can encode it to a Base64 String.

BufferedImageToByteArrayExample1.java

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

public class BufferedImageToByteArrayExample1 {
    public static void main(String... args) throws IOException {
        String imageFilePath = "D:\\SimpleSolution\\qrcode.png";
        File imageFile = new File(imageFilePath);
        BufferedImage bufferedImage = ImageIO.read(imageFile);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
        byte[] bytesOfImage = byteArrayOutputStream.toByteArray();

        String base64String = Base64.getEncoder().encodeToString(bytesOfImage);

        System.out.print(base64String);
    }
}
The output as below.
iVBORw0KGgoAAAANSUhEUgAAAGQAAABkAQAAAABYmaj5AAAA7ElEQVR42tXUsZHEIAwFUHk2cHZuQDO0QeaWTAN4twK3REYbzNAAyhww1ombvd1NbBHeMQS8CPERAH+MAn9YBWCBzAEGTcR13W8cZaEpoLdpiuA6tIb86JWhHnH1tq7vyk4l53MR3fu0p2pZzbJ8JXiqYtHP6H53uBAH3mKadpg0HRZhRrCZNBHzxnWIadBUbILRbK/KzkXxRhEHNpumMuLXLPOZ4IVoz4flA5LTlTzkO+CkqeU/Sgy65G59q92QptbXLIEZVhXQsblDlxZIy8iPDsmrIn5mdiWui/QCoKr2pq35CUPRf/nBPvUNct67nP2Y9j8AAAAASUVORK5CYII=

Happy Coding 😊

Java Convert Byte Array to Base64 String