Search code examples
bashimageimage-processingimagemagickimagemagick-convert

Changing all images in a directory and its sub-directories using a single ImageMagick command?


I have a directory with multi level sub-directories containing .jpg files that I want to change using ImageMagick.

To change a single file I do convert image0.jpg -resize x1000 -quality 82 small_image0.jpg

But how can I do the same but for all the jpgs in every directories, with a single command?

That is:

  • Apply -resize x1000 -quality 82 to every jpg in all of the directories.
  • Every output file should be in the same directory as its input file but with small_ prepended to the name.

Solution

  • With find and bash.

    #!/usr/bin/env bash
    
    path=("$@")
    
    while IFS= read -ru9 -d '' pic; do
       dirname=$(dirname "$pic")
       basename=$(basename "$pic")
       printf 'Converting %s to %s\n' "$pic" "$dirname/small_$basename"
       convert "$pic" -resize x1000 -quality 82 "$dirname/small_$basename" || exit
    done 9< <(find "${path[@]}" -type f -name '*.jpg' -print0)
    

    Assuming you name your script myscript, execute it with the path to the pictures as the argument.

    ./myscript /path/to/pictures
    
    • Change /path/to/pictures with the correct path/directory, or add more path/directory separated by a space e.g. ./myscript path1 path2 anotherpath morepath instead of just one directory.