Compresses a image by providing decreasing its quality - Java 2D Graphics

Java examples for 2D Graphics:Image Compress

Description

Compresses a image by providing decreasing its quality

Demo Code


//package com.java2s;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;

import static javax.imageio.ImageIO.createImageOutputStream;
import static javax.imageio.ImageIO.read;

public class Main {
    /**/*from   w  ww  .j a  va  2 s  .  c  om*/
     * Compresses a image by providing decreasing its quality
     *
     * @param input   the input stream of the the source image
     * @param output  the output stream of the the compressed image
     * @param quality express the quality of compression
     * @param format  image format e.g. jpeg, png, etc.
     * @throws IOException
     */
    private static void compress(final InputStream input,
            final OutputStream output, float quality, String format)
            throws IOException {

        BufferedImage image = read(input);

        // Get a ImageWriter for requested format.
        Iterator<ImageWriter> writers = ImageIO
                .getImageWritersBySuffix(format);
        if (!writers.hasNext()) {
            throw new IllegalStateException("No writers found");
        }

        ImageWriter writer = writers.next();

        // Create the ImageWriteParam to compress the image.
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality);

        // The output will be a ByteArrayOutputStream (in memory)
        ImageOutputStream ios = createImageOutputStream(output);
        writer.setOutput(ios);
        writer.write(null, new IIOImage(image, null, null), param);
        ios.flush();
    }
}

Related Tutorials