title: ImageMagick: scale PNG image with a maximum file-size
body: <p>How would you scale/optimize/minimally output a <em>PNG</em> image so that it just falls below a certain maximum file size? (The input sources are various - PDF, JPEG, GIF, TIFF...)</p>
  
  <p>I've looked in many places but can't find an answer to this question.</p>
  
  <p>In ImageMagick a <em>JPEG</em> output can do this with <code>extent</code> (see e.g. <a href="https://stackoverflow.com/questions/6917219/imagemagick-scale-jpeg-image-with-a-maximum-file-size">ImageMagick: scale JPEG image with a maximum file-size</a>), but there doesn't seem to be an equivalent for other file formats e.g. PNG.</p>
  
  <p>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.</p>
  
  <p>I could also wrap the various (macOS) command-line tools in python.</p>
  
  <p>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.</p>
  
  <p>Thanks for all help.</p>
  
  <p>PS Other relevant questions:</p>
  
  <p><a href="https://stackoverflow.com/questions/19626506/scale-image-according-a-maximum-file-size">Scale image according a maximum file size</a></p>
  
  <p><a href="https://stackoverflow.com/questions/32413523/compress-a-png-image-with-imagemagick">Compress a PNG image with ImageMagick</a></p>
  
  <p><a href="https://stackoverflow.com/questions/45322213/python-set-maximum-file-size-when-converting-pdf-to-jpeg-using-e-g-wand">python set maximum file size when converting (pdf) to jpeg using e.g. Wand</a></p>
  
  <p><strong>Edit:</strong> <a href="https://stackoverflow.com/a/40588202/1021819">https://stackoverflow.com/a/40588202/1021819</a> is quite close too - though the exact code there already (inevitably?) makes some choices about how to go about reducing the file size (<code>resize</code> in that case). Perhaps there is no generalized way to do this without a multi-dimensional search.</p>
  
  <p>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.</p>
  
  <p><a href="https://stackoverflow.com/a/34618887/1021819">https://stackoverflow.com/a/34618887/1021819</a> is also useful, in that it uses Wand, so putting that operation within the binary-chop loop seems to be a way forward.</p>