JPC
JPC

Reputation: 1919

File size increase for pngquant output when using PIL

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.

Upvotes: 4

Views: 910

Answers (2)

hurturk
hurturk

Reputation: 5454

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.

Upvotes: 0

LSerni
LSerni

Reputation: 57388

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.

Upvotes: 3

Related Questions