So I have an image, called square.png
, that is about 3.7 kB in size. I read it into a BufferedImage as so:
BufferedImage img = ImageIO.read("square.png");
At this point I tried writing several different objects to the disk.
ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream("square_out.data"));
I tried the image wrapped in an ImageIcon: stream.writeObject(new ImageIcon(img));
I tried a 2D array of the same size as the pixel dimension of the image (800x600).
I tried wrapping that array in a custom class that implements Serializable and writing that.
All the above techniques resulted in a square_out.data
with a size of about 1.9 MB. That's huge considering the original image was only a handful of kilobytes. It's also odd because the size was exactly the same for each. Is there any reasonable explanation for this/is there a way around it? I'd like to store lots of these, so the absurd file size is bothersome.
Because the BufferedImage
stores the image in uncompressed format internally (and that is what gets serialized).
Use ImageIO.write
to save the image in compressed format.