Convert BufferedImage to byte array - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Convert

Description

Convert BufferedImage to byte array

Demo Code


//package com.java2s;
import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Main {
    private static final String IMAGE_FORMAT = "png";

    /**/*from   w ww  .  j  a  v a 2 s .  com*/
     * Convert {@link BufferedImage} to byte array
     * 
     * @param bufferedImage
     * @return
     * @throws IOException
     */
    public static byte[] bufferedImageToByteArray(
            BufferedImage bufferedImage) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, IMAGE_FORMAT, baos);
        baos.flush();
        byte[] imageInByte = baos.toByteArray();
        baos.close();
        return imageInByte;
    }
}

Related Tutorials