how to compress a PNG image using Java

后端 未结 4 1208
孤街浪徒
孤街浪徒 2020-12-10 12:18

Hi I would like to know if there is any way in Java to reduce the size of an image (use any kind of compression) that was loaded as a BufferedImage and is going to be saved

相关标签:
4条回答
  • 2020-12-10 12:33

    By calling ImageIO.write you use the default compression quality for pngs. You can choose an explicit compression mode which reduces file size a lot.

    String inputPath = "a.png";
    String outputPath = "b.png";
    
    BufferedImage image;
    IIOMetadata metadata;
    
    try (ImageInputStream in = ImageIO.createImageInputStream(Files.newInputStream(Paths.get(inputPath)))) {
        ImageReader reader = ImageIO.getImageReadersByFormatName("png").next();
        reader.setInput(in, true, false);
        image = reader.read(0);
        metadata = reader.getImageMetadata(0);
        reader.dispose();
    }
    
    try (ImageOutputStream out = ImageIO.createImageOutputStream(Files.newOutputStream(Paths.get(outputPath)))) {
        ImageTypeSpecifier type = ImageTypeSpecifier.createFromRenderedImage(image);
        ImageWriter writer = ImageIO.getImageWriters(type, "png").next();
    
        ImageWriteParam param = writer.getDefaultWriteParam();
        if (param.canWriteCompressed()) {
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(0.0f);
        }
    
        writer.setOutput(out);
        writer.write(null, new IIOImage(image, null, metadata), param);
        writer.dispose();
    }
    
    0 讨论(0)
  • 2020-12-10 12:35

    You may want to try pngtastic. It's a pure java png image optimizer that can shrink may png images down to some degree.

    0 讨论(0)
  • 2020-12-10 12:37

    If it's going to be saved as PNG, compression will be done at that stage. PNG has a lossless compression algorithm (basically prediction followed by lempel-ziv compression) with few adjustable parameters (types of "filters") and not much impact in compression amount - in general the default will be optimal.

    0 讨论(0)
  • 2020-12-10 12:43

    Have a look at the ImageWriterParam class in the same package as the ImageIO class. It mentions compression.

    https://docs.oracle.com/javase/7/docs/api/javax/imageio/ImageWriteParam.html

    Also look at the example at http://exampledepot.com/egs/javax.imageio/JpegWrite.html and see if it translates well for PNG files.

    0 讨论(0)
提交回复
热议问题