Reputation: 2936
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?
Upvotes: 4
Views: 2580
Reputation: 111259
The PNG writer supplied 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's possible that imageio-ext or jai-imageio include a png writer with compression support: http://java.net/projects/imageio/
Upvotes: 1
Reputation: 54242
The documentation says it's decoding the input file, so it's not being held in memory as a PNG:
Returns a BufferedImage as the result of decoding a supplied File with an ImageReader chosen automatically from among those currently registered. The File is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned.
When it writes it back, it has to re-encode the PNG file, and Java's PNG encoding doesn't seem to be as efficient as whatever created your original file.
Upvotes: 1
Reputation: 2096
This is most likely due to the compression algorithm being different between Java and whatever created the original PNG.
Upvotes: 5