I was asked to write a program to resize thousands of images which were gonna be uploaded to a website. Images had to be the same height for them to look organized in gallery. I remembered how I used imagemagick to write desktop-clock, immitate tty-clock on wallpaper. That experience helped me to design the program in my mind as we continue to speak on the phone.
/‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾\
| for each image |
| do resize to height=800 |
\___________________________/
O
o \_\_ _/_/
. \__/
(oo)\_______
(__)\ )\/\
||----w |
|| ||
This is a learning opportunity
Since I don't have much of an experience on shell scripting, I was Ducking everything. I learned to do few things during this task.
- For loops in shell script
- Getting list of files
- Correct syntax for resizing with ImageMagick
After reading tutorials and looking at examples everything felt as simple as lego. I just needed to put them together.
Here is image_shrinker.v0.1_alpha.sh
:
#!/bin/sh
mkdir ../output
for image in ./*
do
convert $image -scale 1000000x800 ../output/$image
done
This version has problems which I can't call "feature" 😁️ :
- Resolution is hard coded. Btw, only way to define resolution is in WIDTHxHEIGHT format AFAIK.
- Script must be in same directory as images
- PWD must point to the directory where script is
Adjustable resolution
#!/bin/sh
mkdir ../output
WIDTH=$1 ; HEIGHT=$2
for image in ./*
do
convert $image -scale $WIDTHx$HEIGHT ../output/$image
done
This fixes the hard coded resolution problem but new problem is that the user has to know that WIDTH and HEIGHT must be given. I fix that by showing correct syntax to the user and then exiting :
#!/bin/sh
if [ $# -lt 2 ]
then
echo "USAGE:"
echo -e "\t\$IMAGE_DIRECTORY/image_shrinker.sh WIDTH HEIGHT"
exit 1
fi
WIDTH=$1 ; HEIGHT=$2
mkdir ../output
for image in *
do
convert $image -scale $Resolution ../output/$image
done
Here is some other attempt to make code a bit more flexible in terms of where images can be and where output can go. Actually no but that is what I was going for 😜️
#!/bin/sh
DIR=`pwd`
for image in ./*.*
do
# Below code will scale images to 800px height without breaking aspect ratio
convert $DIR/$image -scale 10000x800 -write $DIR/../output/$image
done
It is hard to ask for help (especially after torturing with my code) but if you would like to give me feedback and advice, reply to toot of this post.