Share

JIU - Java Imaging Utilities

Subscribe

How to compress image?

  1. 2009-10-30 16:54:44 UTC

    my english is poor. i still read the manual and api. you know ,it's a little hard to find it for compress image. so , anyone can give me a example like below?

    Image img = ImageIO.read(file);

    int newWidth ,newHeight;

    BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPEINTRGB);

                 /*
                 * Image.SCALE_SMOOTH ( slow ,quality is not so high. how about JIU ?)                 */ 
    

    tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);

    FileOutputStream out = new FileOutputStream(outputDir + outputFileName);

    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

    encoder.encode(tag);

    out.close();

    thanks !

  2. 2009-11-01 16:16:54 UTC

    Not sure if I understand what you are asking about, but there are two sources for quality loss in the example above. The first is rescaling (which does not involve compression), and the second is saving as JPEG (which involves lossy compression).

    Rescaling can be done using the Resample operation. The resample quality depends on the filter type, I recommend using the "Lanczos3" type if you want high quality rescaling. From the javadoc example:

    Resample resample = new Resample();
    resample.setInputImage(image);
    resample.setSize(image.getWidth() * 3 / 2, image.getHeight() * 3 / 2);
    resample.setFilter(Resample.FILTER_TYPE_LANCZOS3);
    resample.process();
    PixelImage scaledImage = resample.getOutputImage();
    

    JIU doesn't have functionality to save to JPEG (unless I overlooked it), so I have used javax.imageio.ImageWriter for this. If you have an ImageWriter object it is possible to choose the JPEG quality by using the ImageWriteParam object, something like this:

    /* Assume imageWriter is an ImageWriter */
    ImageWriteParam param = imageWriter.getDefaultWriteParam();
    if (param instanceof JPEGImageWriteParam) {
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(0.9);
    }
    /* Assume image is an IIOImage */
    imageWriter.write(null, image, param);
    

    Did this answer your question?

< Previous | 1 | Next >

Add a Reply

This forum does not allow anonymous participation.

Log in to add a reply. Not registered? Create an account to participate and receive email updates when replies are posted to this topic.