I was recently assigned the task of reducing the quality of over 1000 images. My first instinct was to use photoshop’s batch functions to complete the task. After playing around with it for a little while it became apparent that you cannot save files for web with spaces in. Photoshop had failed me. My next idea was to use a bash script to loop over every file and process the image. This was sure to work. Since I have prior experience with image processing I decided to use ImageMagick to complete the task. The command to adjust the quality is:
convert (FILENAME) -quality 50 (FILENAME)
This command is useless on its own so using a for loop I came up with:
for i in $(ls); do
convert $i -quality 50 $i
This script would have worked for me if there were no spaces in the filenames. Because there were it took each filename that had spaces and ran the command on each part of the file name. Unfortunately this was not going to work.
After googling for a while it became apparent that I was not the only person to have the problem of spaces in filenames with for loops. The solution I found was to use the find command and a while loop. Below is working script that successfully completed the task in no time:
find * -iname "*" | \
while read I; do
convert "$I" -quality 50 "$I"
This script could be easily modified to take advantage of ImageMagick’s many other functions. For example it could be used to batch resize a folder of images to make thumbnails by changing the command to:
convert "$I" -resize 200 "$I"
Or it could be used to overlay text onto an image with the following command:
convert "$I" -gravity southeast -annotate +5+10 "thelinuxblog.com" -fill black "$I"
As shown above ImageMagick is really powerful image editing software which can easily be used with the bash shell to process thousands of images with no trouble.