How to convert video to animated gifs from a linux console

Hi,

Today I’m going to show you a very small script that allows you to convert any video (as long as it is supported by mplayer) to a GIF.

Required tools:

* mplayer

* convert

 

mplayer is popular media player available for multiple operating systems that support a wide range of video formats. The convert tool is an utility that lets you convert between multiple image formats among other definitions.  Since the mplayer takes screenshots using jpeg format, we need to use the convert tool to do the convertion to aGIF format.

 

Copy the following code, save it to a file and change its permissions (chmod a+x) and you are ready to roll 🙂

 

 

#!/bin/sh
TMPDIR=/tmp/animated
shopt -s nocaseglob
if [ ! -d "$TMPDIR" ]
then
        mkdir $TMPDIR
fi
 
\rm $TMPDIR/* &> /dev/null
 
if [ $# -lt 3 ]
then
        echo -e "Usage: $0    []\nExample:\n$0 00:15:11 10 myvideo.avi 320:240"
        exit 1
fi
 
if [ -n "$4" ]
then
        SCALE="scale=$4"
fi
 
echo "Generating screenshots. Please be patitent..."
mplayer -ao null -ss $1 -endpos $2 $3 -vo jpeg:outdir=$TMPDIR/ -vf $SCALE &> /dev/null
if [ -f $TMPDIR/00000001.jpg ]
then
        echo "Finished generating frames. Assembling the animated GIF..."
        convert -delay 5 $TMPDIR/*.jpg $TMPDIR/output.gif
        echo "Done! Please check the $TMPDIR/output.gif"
        exit 0
else
        echo -e "Oops\! Something went wrong and the frames were not generated. Check your parameters\!"
        exit 1
fi

Just try it and let me know 😉

4 comments

  1. Doesn’t work I’m afraid. Errors:-

    /home/garf/bin/anigif: 3: /home/garf/bin/anigif: shopt: not found
    /home/garf/bin/anigif: 9: /home/garf/bin/anigif: Syntax error: “&” unexpected

    Interestingly shell options *does* work on our machines when shopt command is executed separately. And I’m sure line 9 is definitely wrong – the bit that reads “&>”

    1. Hi,

      About the “shopt” error I can’t understand why is it happening to you. I already tried this script on several computers and it worked in all of them flawlessly.
      About the second error, you are right but that was due to wordpress parsing html entities. You should really use &> (just to ignore stderr) instead of & and < entities.

      Anyway, I already fixed that. Thanks for the tip 😉

    2. I Remembered another thing.

      I’m assuming that /bin/sh is your current shell but this could be a symlink to a shell other than the a one you are using by default.

      Find out which shell are you using by default ( type this on your console “env | grep SHELL” and check the output) and edit the header of this script to match your current shell.

Leave a Reply to admin Cancel reply

Your email address will not be published. Required fields are marked *