jtlz2
jtlz2

Reputation: 8407

ImageMagick: scale PNG image with a maximum file-size

How would you scale/optimize/minimally output a PNG image so that it just falls below a certain maximum file size? (The input sources are various - PDF, JPEG, GIF, TIFF...)

I've looked in many places but can't find an answer to this question.

In ImageMagick a JPEG output can do this with extent (see e.g. ImageMagick: scale JPEG image with a maximum file-size), but there doesn't seem to be an equivalent for other file formats e.g. PNG.

I could use Wand or PIL in a loop (preference for python) until the filesize is below a certain value, but for 1000s of images this will have a large I/O overhead unless there's a way to predict/estimate the filesize without writing it out first. Perhaps this is the only option.

I could also wrap the various (macOS) command-line tools in python.

Additionally, I only want to do any compression at all where it's absolutely necessary (the source is mainly text), which leaves a choice of compression algorithms.

Thanks for all help.

PS Other relevant questions:

Scale image according a maximum file size

Compress a PNG image with ImageMagick

python set maximum file size when converting (pdf) to jpeg using e.g. Wand

Edit: https://stackoverflow.com/a/40588202/1021819 is quite close too - though the exact code there already (inevitably?) makes some choices about how to go about reducing the file size (resize in that case). Perhaps there is no generalized way to do this without a multi-dimensional search.

Also, since the input files are PDFs, can this even be done with PIL? The first choice is about rasterization, for which I have been using Wand.

https://stackoverflow.com/a/34618887/1021819 is also useful, in that it uses Wand, so putting that operation within the binary-chop loop seems to be a way forward.

Upvotes: 2

Views: 2330

Answers (1)

Glenn Randers-Pehrson
Glenn Randers-Pehrson

Reputation: 12445

With PNG there is no tradeoff of compression method and visual appearance because PNG is lossless. Just go for the smallest possible file, using my "pngcrush" application, "optipng", "zopflipng" or the like.

If you need a smaller file than any of those can produce, try reducing the number of colors to 255 or fewer, which will allow the PNG codec to produce an indexed-color PNG (color-type 3) which is around 1/3 of the filesize of an RGB PNG. You can use ImageMagick's "-colors 255" option to do this. However, I recommend the "pngquant" application for this; it does a better job than IM does in most cases.

Upvotes: 2

Related Questions