Alex Rivera | Logout

decrease image resolution in java

Asked 2011-06-17T19:43:30.260
14

I need to reduce the size of image(not the width and height) using Java program. Is their any good API available for this?

I need to reduce the size from 1MB to about 50kb - 100 kb's. Of-course the resolution will decrease but that doesn't matter.

Edit
Report

1 Answer

7

This is the working code

public class ImageCompressor {
    public void compress() throws IOException {
        File infile = new File("Y:\\img\\star.jpg");
        File outfile = new File("Y:\\img\\star_compressed.jpg");

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                infile));
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(outfile));

        SeekableStream s = SeekableStream.wrapInputStream(bis, true);

        RenderedOp image = JAI.create("stream", s);
        ((OpImage) image.getRendering()).setTileCache(null);

        RenderingHints qualityHints = new RenderingHints(
                RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);

        RenderedOp resizedImage = JAI.create("SubsampleAverage", image, 0.9,
                0.9, qualityHints);

        JAI.create("encode", resizedImage, bos, "JPEG", null);

    }

    public static void main(String[] args) throws IOException {

        new ImageCompressor().compress();
    }
}

This code is Working Great for me. if you need to resize the image then you can change the x and y scale here JAI.create("SubsampleAverage", image, xscale,yscale, qualityHints);

answered 2011-06-17T22:37:52.460

Your Answer