Java BufferedImage to PNG imageToPNG(BufferedImage image)

Here you can find the source of imageToPNG(BufferedImage image)

Description

Converts an image to a PNG stored in a byte array.

License

Open Source License

Parameter

Parameter Description
image a java.awt.image.BufferedImage object.

Return

a byte array with the PNG data

Declaration

public static byte[] imageToPNG(BufferedImage image) 

Method Source Code

//package com.java2s;

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

public class Main {
    /**// www .  j a  va  2 s  .c om
     * Converts an image to a PNG stored in a byte array.
     *
     * @param image a {@link java.awt.image.BufferedImage} object.
     * @return a byte array with the PNG data
     */
    public static byte[] imageToPNG(BufferedImage image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            BufferedImage buffer = new BufferedImage(image.getWidth(null), image.getHeight(null),
                    BufferedImage.TYPE_INT_ARGB);

            buffer.createGraphics().drawImage(image, 0, 0, null);
            ImageIO.write(buffer, "PNG", baos);
            baos.close();
        } catch (IOException e) {
            // todo: log this instead
            e.printStackTrace();
        }

        return baos.toByteArray();
    }
}

Related

  1. imageAsBase64Png(Component c)
  2. imageToPngFile(BufferedImage image, File pngFile)
  3. image(BufferedImage image)
  4. bufferedImageToFile(BufferedImage src, String path)