Resize all images in subdirectories

published on in category linux , Tags: macos linux imagemagick

Table of contents

For a project I was working on, I had a folder structure full of images and wanted to compress them to a specific maximum resolution in-place while retaining the aspect ratio using ImageMagick. The crucial point, as so often, were spaces and special characters in the folder names, making it really hard to use bash loops etc. to make this work. With the NULL character trick, luckily this works pretty well.

The manual of xargs explains it like this:

     -0      Change xargs to expect NUL (``\0'') characters as separators, instead of
             spaces and newlines.  This is expected to be used in concert with the
             -print0 function in find(1).
find . -name "*.jpg" -print0 | xargs -0 mogrify -resize 2200x2200

Short recap:

find searches for all files with the pattern *.jpg, -print0 prints the results with NULL characters instead of spaces as separators. xargs -0 consumes the search results expecting NULL characters and runs mogrify (part of imagemagick) to resize the images in-place.

This way it worked without having any problems with spaces in folder names etc.