allegutta
allegutta

Reputation: 5644

ImageMagick: Convert images into multiple images with different width?

I have a folder with many high-res images (in jpeg, jpg, png). I want to convert every image into images in jpeg with the width of 2500, 1440 and 640, and place them in a folder called output.

I also want to add the width of the image as a suffix to the image filename (i.e. red-ball.jpg -> red-ball-640.jpeg, red-ball-1440.jpeg, red-ball-2500.jpeg).

How can I do this with ImageMagick?

Upvotes: 0

Views: 103

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207345

You can do it like this:

#!/bin/bash

# Make output directory
mkdir output

shopt -s nullglob
for f in *.jpg *.jpeg *.png; do
   base=${f%.*}
   ext=${f##*.}
   echo Converting $f to output/$base -2500 -1440 -640 $ext
   convert "$f" -resize 2500 -write "output/${base}-2500.${ext}" \
                -resize 1440 -write "output/${base}-1440.${ext}" \
                -resize 640 "output/${base}-640.${ext}"
done

Sample Output

Converting test.jpg to output/test -2500 -1440 -640 jpg
Converting z.jpg to output/z -2500 -1440 -640 jpg
Converting z2.jpg to output/z2 -2500 -1440 -640 jpg
Converting z3.jpg to output/z3 -2500 -1440 -640 jpg
Converting z4.jpg to output/z4 -2500 -1440 -640 jpg
Converting z1.jpeg to output/z1 -2500 -1440 -640 jpeg
Converting a.png to output/a -2500 -1440 -640 png
Converting black.png to output/black -2500 -1440 -640 png
Converting c.png to output/c -2500 -1440 -640 png
Converting d.png to output/d -2500 -1440 -640 png
Converting f2.png to output/f2 -2500 -1440 -640 png
Converting gantt.1.png to output/gantt.1 -2500 -1440 -640 png
Converting globe.png to output/globe -2500 -1440 -640 png
Converting h.png to output/h -2500 -1440 -640 png
Converting output.png to output/output -2500 -1440 -640 png
Converting result.png to output/result -2500 -1440 -640 png
Converting result2.png to output/result2 -2500 -1440 -640 png

The shopt -s null glob ensures that if there are no jpg files, or png files in your directory, that the glob (*.jpg or *.png) expands to nothing rather than generating an error message. Further info here.

The ext=${f##*.} finds the shortest thing following a period (full stop), which is basically the file extension. This is called "bash parameter substitution" and the best description I know of is here.

Upvotes: 1

Related Questions