4

If I compress and image with pngquant, and then read and write out with PIL, I see file size increase significantly (sometimes by up to 2x). Anyone have any tips here? I suspect it may have to do with some PIL flags, but not familiar enough with it.

JPC
  • 1,891
  • 13
  • 29

2 Answers2

3

and then read and write out with PIL, I see file size increase significantly (sometimes by up to 2x)

Since PNG is lossless and therefore does not introduce artifacts that might be problematic with other encoders, I see only three real possibilities:

  • you are saving with a different bit depth (e.g. input 8 bits, output 24 bits)
  • you are saving with added alpha information
  • the palette gets heavily reordered (this shouldn't either save or lose more than a few percent, but without seeing the actual image, if 2x is an exceptional case and the rule is closer to 1.2x, it is within the realm of possibility)

For very small files, non-image chunks might be part of the problem if PIL re-adds some data that pngquant removed. Grab some PNG diagnostic tool capable of dumping list and size of all chunks (PLTE, tEXT etc.) and see where the actual increase takes place (Quick google link).

zLib could also be to blame (e.g. if memory serves, advpng uses a tricked-up zlib to increase performance), but not with those numbers, unless we're talking small enough files that even a few bytes might be significant.

LSerni
  • 55,617
  • 10
  • 65
  • 107
  • 1
    I was being an idiot, and changing the bit depth, as you suggested. That combined with some other issues resulted in the blow up. Thanks for the help, particularly since looking back I gave absolutely no context to the question (...sorry, it was a long day). – JPC Mar 30 '17 at 19:39
0

Unless you modify anything RGBA or save with different settings, reading and writing PNG has almost no affect on file size regardless of the library or application you use.

Proof of concept using pngquant generated image and PIL:

$ wget https://pngquant.org/Ducati_side_shadow-fs8.png
$ python
>>> from PIL import Image
>>> im = Image.open("Ducati_side_shadow-fs8.png")
>>> im.rotate(180).save("output.png")
$ stat -c "%s %n" *.png
23405 Ducati_side_shadow-fs8.png
23362 output.png

In example above, output.png is even 43 bytes less than the original. We have rotated it upside down but didn't touch colors or alpha.

hurturk
  • 5,214
  • 24
  • 41