Making GIF Images

You can use the GD library to create GIF images on the fly.

Script II.1.7: circle.pl

 #!/usr/local/bin/perl
 
 # script: circle.pl
 use GD;
 use CGI qw/:standard Map Area/;
 
 use constant RECTSIZE     => 100;
 use constant CIRCLE_RADIUS  => 40;
 %COLORS = (
 	   'white' => [255,255,255],
 	   'red'   => [255,0,0],
 	   'green' => [0,255,0],
 	   'blue'  => [0,0,255],
 	   'black' => [0,0,0],
 	   'bisque'=> [255,228,196],
 	   'papaya whip' => [255,239,213],
 	   'sienna' => [160,82,45]
 	   );
 
 my $draw          = param('draw');
 my $circle_color  = param('color') || 'bisque';
 my $mag           = param('magnification') || 1;
 
 if ($draw) {
     draw_image();
 } else {
     make_page(); # <== TYPO IN HANDOUT!
 }
         
 sub draw_image {
     # create a new image
     my $im = new GD::Image(RECTSIZE*$mag,RECTSIZE*$mag);
 
     # allocate some colors
     my $white = $im->colorAllocate(@{$COLORS{'white'}});
     my $black = $im->colorAllocate(@{$COLORS{'black'}});       
     my $circlecolor = $im->colorAllocate(@{$COLORS{$circle_color}});
 
     # make the background transparent and interlaced
     $im->transparent($white);
     $im->interlaced('true');
 
     # Put a black frame around the picture
     $im->rectangle(0,0,RECTSIZE*$mag-1,RECTSIZE*$mag-1,$black);
 
     # Draw the circle
     $im->arc(RECTSIZE*$mag/2,RECTSIZE*$mag/2,CIRCLE_RADIUS*$mag*2,CIRCLE_RADIUS*$mag*2,0,360,$black);
 
     # And fill it with circlecolor
     $im->fill(RECTSIZE*$mag/2,RECTSIZE*$mag/2,$circlecolor);
 
     # Convert the image to GIF and print it
     print header('image/gif'),$im->gif;
 }
 
 sub make_page {
     print header(),
           start_html(-title=>'Feeling Circular',-bgcolor=>'white'),
           h1('A Circle is as a Circle Does'),
           start_form,
           "Magnification: ",radio_group(-name=>'magnification',-values=>[1..4]),br,
           "Color: ",popup_menu(-name=>'color',-values=>[sort keys %COLORS]),
           submit(-value=>'Change'),
           end_form;
     print em(param('message')) if param('message');

     param(-name=>'draw',-value=>1);
     print
          img({-src=>self_url(),-alt=>'a circle',
 	       -align=>'LEFT',-usemap=>'#map',
 	       -border=>0});
     Delete('draw'); 

     print Map({-name=>'map'},
 	      Area({-shape=>'CIRCLE',
 		    -href=>param(-name=>'message',-value=>"You clicked in the circle")
 			   ? self_url() : '',
 		    -coords=>join(',',RECTSIZE*$mag/2,RECTSIZE*$mag/2,CIRCLE_RADIUS*$mag),
 		    -alt=>'Circle'}),
 	      Area({-shape=>'RECT',
 		    -href=>param(-name=>'message',-value=>"You clicked in the square")
 			   ? self_url() : '',
 		    -coords=>join(',',0,0,RECTSIZE*$mag,RECTSIZE*$mag),
 		    -alt=>'Square'}));
     print end_html;
 }

What it Looks Like

http://localhost/cgi-bin/conference/circle.pl
<< Previous Contents >> Next >>

Lincoln D. Stein, lstein@cshl.org
Cold Spring Harbor Laboratory
Last modified: Mon Aug 17 10:47:33 EDT 1998