initial commit
[xkcd-annotator.git] / xkcd-annotator.sh
1 #!/bin/bash
2
3 # annotate xkcd comics with title and alt-text
4 # copyright Felix Kästner (fpunktk), GPL
5 # expected fileformat: [^-]*-[0-9]+-.*\.(jpg|png)
6
7 title_font="/usr/share/fonts/truetype/freefont/FreeSansBold.ttf"
8 title_size="26"
9 alt_font="/usr/share/fonts/truetype/freefont/FreeSans.ttf"
10 alt_size="16"
11 sourcedir="./"
12 destdir="./xkcd-converted/"
13 minwidth="500"
14 am="1" # alt-text margin left and right
15
16 # change margin for alt-text to manually prevent overflow
17 case "$1" in
18     [0-9]|[1-9][0-9])
19         [ $1 -lt $(($minwidth / 10)) ] && am="$1"
20     ;;
21 esac
22
23 mkdir -pv "$destdir"
24
25 for fn in xkcd*.png xkcd*.jpg
26 do
27     [ -f "$fn" ] || continue
28     echo "$fn"
29     # get width and height from the original image
30     read cw ch <<<$(identify -format '%w %h' "$fn")
31     w="$cw"
32     [ $w -lt $minwidth ] && w="$minwidth"
33     # extract the number (between the -)
34     nn="${fn#*-}"
35     nn="${nn%%-*}"
36     # download the json with the image information if it does not exist
37     [ -r "$destdir${fn%\.*}.json" ] || wget -q -O "$destdir${fn%\.*}.json" "http://xkcd.com/$nn/info.0.json"
38     json="$(cat "$destdir${fn%\.*}.json")"
39     # extract title-text and alt-text from json (dirty hack, might break things)
40     tt="${json#*\"title\": \"}"
41     tt="${tt%%\", *}"
42     at="${json#*\"alt\": \"}"
43     at="${at%%\", *}"
44     # write title-text (with number) and alt-text to a new png image
45     convert -background white -border 2x0 -bordercolor white -fill black -font "$title_font" -pointsize "$title_size" -size $(($w-4))x -gravity Center caption:"xkcd $nn: $tt" tt.png
46     # TODO: sometimes text gets cut off for no obvious reason, can be prevented by specifying margin $am
47     convert -background '#FFF9BD' -bordercolor '#FFF9BD' -border ${am}x0 -bordercolor black -border 1x1 -fill black -font "$alt_font" -pointsize "$alt_size" -size $(($w-2-$am-$am))x -gravity Center caption:"$at" at.png
48     # get height from the new images
49     th="$(identify -format '%h' tt.png)"
50     ah="$(identify -format '%h' at.png)"
51     echo -e "$nn $w $ch $th $ah \n$tt \n$at \n"
52     # combine the images
53     convert -size ${w}x$(($ch+$th+$ah+5)) "xc:white" tt.png -geometry +0+0 -composite "$fn" -geometry +$((($w-$cw)/2))+$th -composite at.png -geometry +0+$(($th+$ch+5)) -composite "$destdir${fn%\.*}.png"
54     # delete temporary images
55     rm tt.png at.png
56 done
57