I have an image which contains multiple images in it. I want to split the image into multiple image files, one file per image. How do I do this using ImageMagick?
I have attached a sample image file.
Best Answer
To simply split your image into quadrants (same size) use crop+repage:
#!/bin/bash
# $1 : first gif
# $2 : second gif
mkdir first
cd first
convert $1 x%04d.gif
cd ..
mkdir second
cd second
convert $2 x%04d.gif
cd ..
for filename in first/*
do
filename=`basename $filename`
montage -tile 2x1 -geometry 512x512 first/$filename second/$filename concat$filename
done
convert concat* output.gif
rm -rf first
rm -rf second
rm concat*
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.
Best Answer
To simply split your image into quadrants (same size) use
crop+repage
:If you need different size quadrants you could cut around a single point: