Script to bulk resize images

Published: Fri 01 June 2018

Intro

A quick script I wrote to create resized copies of all the images in a folder to a given percentage of the original size, copied to a new subfolder in turn with the new geometry in the image filename (which I find helpful). For instance, if you had a folder named Poland containing a gazillion images you wished to have at 20% their current size, you would:

./bulk-image-resize.sh Poland 20

This would result in a new sub directory resized containing the directory 20 with copies of the images at 20% their former size.

I find it handy. Perhaps you do too.

Code

This script has been tested on Debian GNU/Linux 9.2 on JPEG, PNG, GIF and TIFF files. It should work fine on any UNIX or UNIX like OS with the excellent ImageMagick suite.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/bin/bash

# Resize all images in the given folder to a percentile. 
# Requires ImageMagick via your GNU/Linux distribution or OS at https://www.imagemagick.org/
# 
# Save as bulk-image-resize.sh, 'chmod +x bulk-image-resize.sh' and run:
#
#   ./bulk-image-resize.sh [PATH TO FOLDER] [PERCENT]
#
# You're welcome,
# Julian Oliver, 2018 
# https://julianoliver.com

DIR=$1 #fullpath
SCALE=.$2 # Input variable $2 is a percentile, where 75 = 75%
TDIR=resized/$2 # Variable for our target directory (for instance, 'Poland/resized/75')

if [ $# -lt 2 ]; then
    echo "Usage: ./bulk-image-resize.sh [PATH TO FOLDER] [PERCENT]"
    exit 0
fi

cd $DIR

# Check for target directory, create if it doesn't already exist 
if [ ! -d $TDIR ]; then
    mkdir -p $TDIR
else
    echo "Directory $TDIR already exists"
fi

for img in *; do  
    # Check we're working with images 
    ft=$(file $img |  awk '{split($0,a,":"); split($0,b," "); print $3}')
    if [[ $ft == "image" ]]; then
        echo Found image $img
        # Get width and height of original image
        wh=($(identify $img | awk '{ gsub(/x/," "); print $3" "$4 }'))
        w="${wh[0]}";h="${wh[1]}"
        # Calculate target geometry for our filename
        tw=$(echo "scale=3;$SCALE*$w" | bc)
        th=$(echo "scale=3;$SCALE*$h" | bc)
        tsize=$(echo $tw"x"$th | sed 's/\.00//g')
        # Our target image filename
        target=$(echo $img | sed "s/\./_$tsize\./")
        echo Original size is $w"x"$h
        echo Target size is: $tsize 
        # Create a resized copy of the image to a folder in the target directory 
        echo Converting image to $target
        convert -resize $tsize $img $TDIR/$target  
    else
        echo "Not an image, leaving alone"
    fi
done

Affiliated