Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PNG read and write with Java increases file size

Got a problem when reading and writing a png file. I read it with ImageIO to a byte array and then write this byte array again using ImageIO. But the file size increases 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 up: is there any library to support compressed PNGs that is written in Java and does not need any native code?

like image 615
bertolami Avatar asked May 22 '12 16:05

bertolami


1 Answers

This is most likely due to the compression algorithm being different between Java and whatever created the original PNG.

like image 76
Dan Armstrong Avatar answered Oct 02 '22 08:10

Dan Armstrong