Brief BASH script to convert animated GIFs to 3GP video clips.

I was working on an Android app recently, and found myself if a situation where I needed to use some animated GIF images, but I discovered that they wouldn’t render properly outside of a browser context. The simplest solution was to put together a quick script to convert animated GIFs to tiny Android-compatible 3GP video clips. I’ve not seen any published solutions to this problem, so I’m posting it here in case it’s useful to anyone else.

This script makes use of Imagemagick and avconv from libav (formerly ffmpeg) to do the heavy lifting, so you’d need these installed (on a debian-based system, including derivatives such as Linux Mint or Ubuntu, that’s sudo apt-get install imagemagick and sudo apt-get install libav-tools respectively). The resulting video clips are H.263 encoded video streams in the 3GP wrapper, but this can be tweaked, of course. Perhaps this will be handy to someone.

 1 #!/bin/bash
3 usage="
4 Usage: $0 <input_file.gif>
5 "
7 exists() { which "$1" &> /dev/null ; }
9 if ! exists convert ; then
10     echo "ImageMagick is required (hint: sudo apt-get install imagemagick)!" 1>&2;
11     exit 1;
12 fi
14 if ! exists avconv ; then
15     echo "AVConv is required (hint: sudo apt-get install libav-tools)!" 1>&2;
16     exit 1;
17 fi
19 if [ ! -e "$1" ]; then
20     echo "File '$1' does not exist!";
21     echo $usage;
22     exit
23 fi
25 GIF="$1"
26 IMGMASK="${GIF/.gif/-%04d.png}";
28 TMPDIR=$(mktemp -d);
29 trap 'rm -rf "$TMPDIR"' EXIT INT QUIT TERM;
31 echo -n "splitting GIF into frames...";
32 convert -coalesce "$GIF" "$TMPDIR/$IMGMASK";
33 echo " done!";
35 echo -n "combining frames into video...";
36 avconv -f image2 -i "$TMPDIR/$IMGMASK" $TMPDIR/intermediate.mp4 &> /dev/null;
37 echo " done!";
39 echo -n "converting video to Android format...";
40 avconv -i $TMPDIR/intermediate.mp4 -y -s qcif -vcodec h263 -r 10 -b 180k "${GIF/.gif/.3gp}" &> /dev/null;
41 echo " done!";