Search code examples
linuximageoptimizationimagemagickbulk

How to use ImageMagick convert command for all images in subfolders


For single files, I am using the following ImageMagick commands (as google suggests):

For png

convert file.png -sampling-factor 4:2:0 -strip -quality 85 -interlace PNG -colorspace sRGB file.png

For jpg

convert file.jpg -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace sRGB file.jpg

But I need to do the same for all .jpg in a subfolder

I tried this:

find ./*.jpg | xargs convert $ -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace sRGB $

And all the images where compressed but named with the name of the first one with an added index, example:

/img/first-one-0.jpg  
/img/first-one-1.jpg  
/img/first-one-2.jpg  
/img/first-one-3.jpg  
...

How could I do It in bulk overriding originals? Even if we have multiple sub-dirs:

/img/dir-1/one.jpg  
...  
/img/dir-2/foo.jpg  

Solution

  • If you want to overwrite all the files in a directory, use mogrify:

    mogrify -sampling-factor 4:2:0 -strip -quality 85 -interlace PNG -colorspace sRGB *.png
    

    If you want the results written in a new sub-directory called processed:

    mkdir processed
    mogrify -path processed ...
    

    If you are on ImageMagick v7 or newer, that becomes:

    mkdir processed
    magick mogrify -path processed ...