Making Animated GIF Images

Combine the GD library with the ImageMagick combine program.

Or use the Image::Magick module directly.

Idea is to execute:

  convert /usr/tmp/animate2345/picture0.png \
          /usr/tmp/animate2345/picture1.png \
          /usr/tmp/animate2345/picture1.png \
          gif:-

Script II.1.8: animate.pl

 #!/usr/local/bin/perl
 
 # script: animated.pl
 use GD;
 use File::Path;
 
 use constant START      => 80;
 use constant END        => 200;
 use constant STEP       => 10;
 use constant COMBINE    => '/usr/local/bin/convert';
 @COMBINE_OPTIONS = (-delay => 5,
 		     -loop  => 10000);
 
 @COLORS = ([240,240,240],
 	   [220,220,220],
 	   [200,200,200],
 	   [180,180,180],
 	   [160,160,160],
 	   [140,140,140],
 	   [150,120,120],
 	   [160,100,100],
 	   [170,80,80],
 	   [180,60,60],
 	   [190,40,40],
 	   [200,20,20],
 	   [210,0,0]);
 @COLORS = (@COLORS,reverse @COLORS);
 
 my @FILES = ();
 my $dir = create_temporary_directory();
 my $index = 0;
 for (my $r = START; $r <= END; $r+=STEP) {
     draw($r,$index,$dir);
     $index++;
 }
 for (my $r = END; $r > START; $r-=STEP) {
     draw($r,$index,$dir);
     $index++;
 }
 
 # emit the GIF89a
 $| = 1;
 print "Content-type: image/png\n\n";
 system COMBINE,@COMBINE_OPTIONS,@FILES,"gif:-";
 
 rmtree([$dir],0,1);
 
 sub draw{
     my ($r,$color_index,$dir) = @_;
     my $im = new GD::Image(END,END);
     my $white = $im->colorAllocate(255,255,255);
     my $black = $im->colorAllocate(0,0,0);
     my $color = $im->colorAllocate(@{$COLORS[$color_index % @COLORS]});
     $im->rectangle(0,0,END,END,$white);
     $im->arc(END/2,END/2,$r,$r,0,360,$black);
     $im->fill(END/2,END/2,$color);
     my $file = sprintf("%s/picture.%02d.png",$dir,$color_index);
     open (OUT,">$file") || die "couldn't create $file: $!";
     print OUT $im->png;
     close OUT;
     push(@FILES,$file);
 }
 
 sub create_temporary_directory {
     my $basename = "/usr/tmp/animate$$";
     my $counter=0;
     while ($counter < 100) {
 	my $try = sprintf("$basename.%04d",$counter);
 	next if -e $try;
 	return $try if mkdir $try,0700;
     } continue { $counter++; }
     die "Couldn't make a temporary directory";
 }

What it Looks Like


<< Previous Contents >> Next >>

Lincoln D. Stein, lstein@cshl.org
Cold Spring Harbor Laboratory
Last modified: Sat Jun 3 19:57:51 AKDT 2000