Batch image resizing with Imagemagick

Automate resizing images on Linux

This tutorial shows you how to list your images in a csv file and resize every image in that list automatically.
WHOOO! AUTOMATION! πŸŽ‰

Imagemagick

ImageMagick is a free and open-source software suite for displaying, converting, and editing raster image and vector image files. 

Prepare the scripts

  • Log in your Linux system
  • Run the following command in your bash console to list every JPG in the specified folder recursively and save it into a csv file
find /home/project/ -name "*.jpg" -print| while read LINE; do echo "$LINE" ; done > list_with_images.csv
  • Create a file named “resize_with_imagemagic.sh”
# define the settings
export MAGICK_THREAD_LIMIT=1;
export MAGICK_THROTTLE_LIMIT=100;
export MAGICK_MEMORY_LIMIT=500mb;

start=0;
end=$(cat $1 | wc -l)
# loop through every line of the given file
while read file; do
    echo "[x] Optimizing $file"
    echo $(($end-$((++start)))) elements remaining of $end
    replace="_optimized.jpg"
    targetFile="${file/.jpg/_optimized.jpg}"
    echo "Optimizing $file to $targetFile"
    convert "$file" -resize 1920 "$targetFile"
    # let the CPU rest for 10 sec
    sleep 10
done < $1

You can edit the script to your liking. it doesn’t replace the original image, but creates a new one with a postfix of “_optimized”.
Original: test_image.jpg
Optimized: test_image_optimized.jpg

Run the script

sh resize_with_imagemagic.sh list_with_images.csv

Learn more about Linux bash tricks

Author: Mitchel Pawirodinomo

Software Engineer | Pentester | FX Trader

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.