PNG reading and writing from Java increases file size

There was a problem reading and writing the png file. I read it with ImageIO in a byte array, and then write this byte array again using ImageIO. But the file size is increasing significantly. How can this happen?

public BufferedImage toBufferedImage(InputStream inputstream) {
    try {
        return ImageIO.read(inputstream);
    } catch (Exception e) {
        throw new IllegalStateException("Can't convert to buffered image", e);
    }
}

public byte[] toByteArray(BufferedImage bufferedImage, String filetype) {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    try {
        ImageIO.write(bufferedImage, filetype, output);
        return output.toByteArray();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

Follow after : is there any library to support compressed PNGs written in Java and doesn’t need any native code?

+3
source share
3 answers

The documentation says that it decodes the input file, so it is not stored in memory as PNG:

BufferedImage ImageReader, . ImageInputStream. ImageReader , null.

, PNG , Java PNG , .

+1

, , , Java , PNG.

+5

The PNG writer that ships with the JDK does not support compression. You can quickly check this with:

w = ImageIO.getImageWritersByFormatName("png").next();
p = w.getDefaultWriteParam();
print("Can compress? "+p.canWriteCompressed());
// Can compress? false

It is possible that imageio-ext or jai-imageio include a compression-enabled png record: http://java.net/projects/imageio/

+1
source

All Articles