如何使用Java压缩PNG图像

嗨,我想知道Java中是否有任何方法可以减少作为BufferedImage加载的图像大小(使用任何类型的压缩),并将保存为PNG。

也许某种png imagewriteparam? 我没有找到任何有用的东西,所以我卡住了。

下面是一个示例如何加载和保存图像

public static BufferedImage load(String imageUrl) { Image image = new ImageIcon(imageUrl).getImage(); bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D g2D = bufferedImage.createGraphics(); g2D.drawImage(image, 0, 0, null); return bufferedImage; } public static void storeImageAsPng(BufferedImage image, String imageUrl) throws IOException { ImageIO.write(image, "png", new File(imageUrl)); } 

如果it's going to be saved as PNG ,则将在该阶段进行压缩。 PNG具有无损压缩算法(基本上是预测,然后是lempel-ziv压缩),具有很少的可调参数(“ 滤波器 ”类型)并且对压缩量没有太大影响 – 通常,默认值是最佳的。

你可能想试试pngtastic 。 这是一个纯粹的java png图像优化器,它可以缩小到某种程度的png图像。

在与ImageIO类相同的包中查看ImageWriterParam类。 它提到了压缩。

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

另请参阅http://exampledepot.com/egs/javax.imageio/JpegWrite.html上的示例,看看它是否可以很好地转换为PNG文件。