write Image to byte array - Java 2D Graphics

Java examples for 2D Graphics:Image Load

Description

write Image to byte array

Demo Code

/*// w  w w .j  a  v  a  2 s  . c  om
 * Copyright 2000-2013 Enonic AS
 * http://www.enonic.com/license
 */
//package com.java2s;

import java.awt.image.BufferedImage;

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

import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.MemoryCacheImageOutputStream;

public class Main {
    public static int minSizeForProgressiveLoading;

    public static byte[] writeImage(BufferedImage image, String format,
            int quality, boolean canBeProgressive) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writeImage(out, image, format, quality, canBeProgressive);
        return out.toByteArray();
    }

    public static void writeImage(OutputStream out, BufferedImage image,
            String format, int quality, boolean canBeProgressive)
            throws IOException {
        ImageWriter writer = getWriterByFormat(format);
        writer.setOutput(new MemoryCacheImageOutputStream(out));
        ImageWriteParam params = writer.getDefaultWriteParam();
        setCompressionQuality(params, quality);
        final int pixels = image.getHeight() * image.getWidth();
        if (canBeProgressive && minSizeForProgressiveLoading != -1
                && pixels > minSizeForProgressiveLoading
                && params.canWriteProgressive()) {
            params.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);
        }
        writer.write(null, new IIOImage(image, null, null), params);
        writer.dispose();
    }

    public static ImageWriter getWriterByFormat(String format) {
        Iterator<ImageWriter> iter = ImageIO
                .getImageWritersByFormatName(format);
        if (iter.hasNext()) {
            return iter.next();
        } else {
            throw new IllegalArgumentException("Image format [" + format
                    + "] is not supported");
        }
    }

    private static void setCompressionQuality(ImageWriteParam params,
            int quality) {
        if (quality <= 0) {
            quality = 1;
        }

        if (quality > 100) {
            quality = 100;
        }

        try {
            params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            params.setCompressionQuality((float) quality / 100f);
        } catch (Exception e) {
            // DO nothing since compression not supported
        }
    }
}

Related Tutorials