Question about serializing PNG images


Hi everyone,

I am having a problem with file sizes when loading a PNG image, serializing it into a file, and then reloading the saved file and serializing it again. I have read another post about JPG compression sizes and this could be the same thing, but I am explaining my problem just in case I am talking about different things.

The code is shown below:

const Image img = ImageFileFormat::loadFrom("aa.png");

File file = File("image.dat");

ScopedPointer <FileOutputStream> destStream = file.createOutputStream();

PNGImageFormat pngimage;
pngimage.writeImageToStream(img, *destStream);

After this, the size of image.dat is 5067 bytes.

Then I load the image and save it again:

FileInputStream inputStream(file); //"image.dat"

const Image img2 = ImageFileFormat::loadFrom(*inputStream);

ScopedPointer <FileOutputStream> destStream2 = file.createOutputStream();

PNGImageFormat pngimage2;

pngimage2.writeImageToStream(img2, destStream2);

After this, the size of image.dat is 5070 bytes.

If you do this repeteadly, file size keeps getting bigger. I have to admit every image loads and saves correctly.

What is happening?. Is it the same reason of the other post about JPG compression algorithm?

Thanks to all,




Looks like you're appending new data onto the end of the existing file - try deleting the file first.


I am deleting the file first, before opening the stream:


This is how I have code(I didn't write the whole code in my post)


   bool bIsDeleted = file.deleteFile();
   if (bIsDeleted && file.hasWriteAccess())
      ScopedPointer <FileOutputStream> destStream = file.createOutputStream();

      ..... //Write the file



So that's not the problem.





Then you're probably somehow not deleting the stream, so that it's not all getting flushed?


I've tried using a normal pointer (and deleting it) to create the OutputStream instead of using a ScopedPointer, just in case. The problem remains. I think I might not be deleting the stream, because I have tested the same code to serialize other data such as ValueTree or Fonts and in those cases it does correctly. 

I realised too that PNGImageFormat::writeImageToStream() compresses the image (Original size of my PNG is 6.913 bytes and after loading and serializing using writeImageToStream() it reduces size to 5067 bytes as I said in my first post). May it be related somehow with this function after all?

Anyway, Thanks Jules.