Thursday, August 09, 2012

Speed Scripting 2 - Flag Mashup

OK, so my previous script grabbed the full set of 204 flags of Olympic nations/territories/etc. - but what to do with them?

Well, they're all the same size, so a mashup is fairly straightforward.  I went with a 17x12 matrix, so it would come out evenly.  I'm something of a neophyte with image manipluation in Linux, so I'm sure that someone "has a better way" to accomplish the task, but I'm a command-line type of guy - no GIMP for me!

I used pngtopnm and pnmcat (from the netpbm package) and convert (from the imagemagick package) to get the job done.  I won't go into a line-by-line dissection of the script, so here you go:

#!/bin/sh
#
# convflags -convert flag images from olympic website and do a straight mashup
#
ABFILE=/home/wmorgan/olyflags/abbreviations
COUNT=1
#
cat $ABFILE | while read country
do
echo Converting $country
pngtopnm $country.png > $country.ppm
done
echo
echo Creating rows of 12...
echo
ls *.ppm | xargs -n12 | while read line
do
pnmcat -lr $line > $COUNT.big.ppm
echo Row $COUNT done...
COUNT=`expr $COUNT + 1`
done
echo
echo Concatenating rows top to bottom...
echo
ls *.big.ppm | sort -n | xargs pnmcat -tb > flags.ppm
echo Converting to JPEG and cleaning up
convert flags.ppm flags.jpg
mv flags.ppm flags.ppm.tmp
rm *.ppm
mv flags.ppm.tmp flags.ppm
echo
echo Done!
echo

The one trick I will point out is the use of "sort -n" in the "top to bottom" step. Since I used the COUNT variable to name the files, I had files named "1.big.ppm", "2.big.ppm", etc...but that could be problem with more than 9 files; when you use ls, its default sorts by first character, so you'd get "1.big.ppm 10.big.ppm 11.ppm [...] 2.big.ppm", which is NOT what I wanted (since the images are in alpha order by country code).  Throwing "sort -n" between the ls and xargs/pnmcat commands made sure that the row images were stacked in the proper order.

The result?  Glad you asked...here's the JPG: