How to rescale several images to same size

imagemagickimagesscripting

I have several image files in a directory. These images are similar size and have same background color.

How can I make all images same size by adding background like this attached image?

enter image description here

Best Answer

This should work with all the image types that ImageMagick can handle without having to specify *.png, *.jpg, *.jpeg etc:

#!/bin/bash

images=$(identify -format '%f\n' * 2>/dev/null)

IFS=$'\n'
set -e

max_dims=$(
  identify -format '%w %h\n' $images 2>/dev/null |
  awk '($1>w){w=$1} ($2>h){h=$2} END{print w"x"h}'
  )

orig_dir=originals_$(date +%Y-%m-%d_%T)
mkdir "$orig_dir"
mv -- $images "$orig_dir"
cd "$orig_dir"

set +e

for image in $images; do
  convert -- "$image" -gravity Center -extent "$max_dims" "../$image"
done

This will move the original images into a dated directory in case the results are not desirable. Also, this will fail if, for whatever reason, the image files have newlines in their names.

This script could do with some more error messages to give a helpful indication if anything went wrong. But for now if there is any error moving the images (everything between the set -e and set +e), the script will exit. Hopefully this will avoid doing any irreversible damage.

Update

Now with awk script shamelessly plagiarised from @terdon's answer.

Related Question