Search code examples
javascriptterminalapplescriptphotoshopautomator

Optimizing image to fit max file size


I need to create a simple application that allows me to drag and image(s) onto and it will opimize the image below a certian file size.

I currently have a long drawn-out process in Photoshop where I have to save multiple images at once, reopen each, and export as the correct file size. The dimensions are always the same though. So 300x300 will always be below 40kbs, while the 100x600 will always be 35kbs.

Even if I'm running the images through Photoshop the same exact way. I was just hoping there'd be a faster/automated process but I'm having a lot of trouble finding one.

Any ideas?

Thanks in advance.

Note: I don't want to change the image size (dimensions) only the file size (kbs).


Solution

  • You can do that with ImageMagick which is installed on most Linux distros and is available for macOS and Windows. It only works for JPEG (because that allows trading image size for quality), whereas PNG does not - explicitly, at least.

    So, say your image is 300x300 and particularly large at 161kB because it is incompressible random noise:

    enter image description here

    -rw-r--r--   1 mark  staff  161310 15 Feb 16:56 input.jpg
    

    You can reduce it to your desired 40kB with this command in Terminal (or Command Prompt if under Windows):

    magick input.jpg -define jpeg:extent=40kb result.jpg
    

    And the result is 39kB:

    -rw-r--r--   1 mark  staff   39119 15 Feb 16:58 result.jpg