Search code examples
imageimage-processingimagemagickimagemagick-convert

Downscaling image file size using imageMagick


I am trying to find out an imagemagick operation to reduce image filesize by decreasing its quality.

This operation works

convert -fuzz 1% -trim -quality 90 -limit memory 32MiB  original.jpg  converted.jpg

Reducing the quality factor will decrease the imageSize. Is there any other way of acheaving the same and adding a limit of MAX_SIZE.

For example 5Mb image should be downsized to 2Mb


Solution

  • You would use -define jpeg:extent=....

    Here is an example with a large image of random data that would need a very large file size to accurately represent it with any reasonable quality.

    convert -size 10000x1000 xc:gray +noise random -define jpeg:extent=2MB out.jpg
    

    Result

    -rw-r--r--    1 mark  staff  1844050 15 May 10:44 out.jpg
    

    And check the quality used:

    identify -format "%Q" out.jpg 
    21
    

    Another example:

    convert -size 10000x1000 xc:gray +noise random -define jpeg:extent=400kb out.jpg
    

    Result

    -rw-r--r--    1 mark  staff   377757 15 May 10:44 out.jpg
    

    And check the quality used:

    identify -format "%Q" out.jpg 
    5
    

    If you want a way to do something similar with Python, I wrote an answer that works pretty well here. It does a binary search for a JPEG quality that satisfies a maximum size requirement.