简体   繁体   中英

Compress 2d graphics written image size in java

I have an image and using java.awt.Graphics2D in java I have written a text on the image. Everything works fine until here. When I tried to compress this image in java using ImageWriteParam in java the picture gets overblown. Below is the code which I used to compress the image size. This code works fine for normal images though.

    File input = new File("Input Image File");
    BufferedImage image = ImageIO.read(input);

    File compressedImageFile = new File("Compressed image file location");
    OutputStream os = new FileOutputStream(compressedImageFile);

    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
    ImageWriter writer = (ImageWriter) writers.next();

    ImageOutputStream ios = ImageIO.createImageOutputStream(os);
    writer.setOutput(ios);

    ImageWriteParam param = writer.getDefaultWriteParam();

    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality(1.0f);  // Change the quality value you prefer
    try {
        writer.write(null, new IIOImage(image, null, null), param);
        System.out.println(writer);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    os.close();
    ios.close();
    writer.dispose();

Any help is appreciated. Thanks !

you use the default ImageWriterParams , using writer.getDefaultWriteParam() . But as mentioned in the API of the ImageWriter it says here:

[...] The default implementation constructs and returns a new ImageWriteParam object that does not allow tiling, progressive encoding, or compression ...

there is also a hint on how to handle that issue,

individual plug-ins may return an instance of ImageWriteParam with additional optional features enabled , or they may return an instance of a plug-in specific subclass of ImageWriteParam.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM