27 February 2007

Flags and ImageMagick

This day I was looking for some flags to use for chess engines. A quick locate flag |grep .png gave me a lot of lines like /usr/share/locale/ l10n/us/flag.png. The flags looked like this and were originally created as a part of kdebase.

I quickly colleckted the files by

for i in `ls /usr/share/locale/l10n/`
    cp /usr/share/locale/l10n/$i/flag.png $i.png

I found out however, that those flags were boring. They also didn't look enough like computers. I used to use this icon: (stock_notebook) for engnines, and I figured that it would be fun to merge the flags and the notebooks.

I tried out stuff in the gimp, and it worked well. Now the problem was that I had 229 flags for which I had to open in gimp, resize, copy to the notebook image and save. A quick calculation based on the amount of time spent on the first flag, showed me that this would take me 1.9 hours. If of course I ever managed to complete it.

This brought up ImageMagick to my mind. ImageMagick which is a command line utility for doing quite a lot of advanced image operations. I found the "Usage guide" and read these two parts of it: resize, composite, which described exactly the functions I needed: Resizing and merging.

In the beginning the guide was looking kinda messy, mostly because of the length of the command lines. However it quickly became clear that it was really very well built, with screenshots all over it, white made it easy to find what I was looking for.

The resize command looked like the following: convert in.png -resize 14x7\! out.png. The ! told ImageMagick that I didn't care about the original aspect of the image, which is necessary since all flags have different formats.

Next the scaled image had to be merged on the notebook image. The command for such an operation was: composite -geometry +5+6 2.png stock_notebook.png 3.png. The geometry option told how much to translate the upper image (2.png) on the lower.

At this point I already had a nearly perfect image. The only missing part was the border around the screen being too thin. To help this problem I decided to merge again with a half transparent white rectangle: The operation was mostly like the previous, only without the translation as the rectangle image had the same size as the notebook image. composite -geometry +0+0 light.png 3.png 4.png did its thing.

In the end I put down everything to these few lines:

for i in `ls`
    echo "doing $i"
    convert $i -resize 14x7\! $i
    composite -geometry +5+6 $i ../stock_notebook.png $i
    composite -geometry +0+0 ../light.png out.png out2.png
And in 10 seconds, ImageMagick did what would otherwise have taken me hours. Nice :)

1 comment:

tonic_whp said...

Hi Thomas, one should ask how long did take to learn ImageMagick to solve your problem. But even if it took longer the 1.9 hours it sure was more fun :)!