When you are building web pages for a newspaper, you have a lot of images. Every story might have a photo, every section has navigation graphics, every ad is a GIF. Adding width and height attributes to the <img> tags gives the browser the image dimensions before it fetches the image, so it can reserve that space as the page loads.
The problem is that we have hundreds of images, and nobody wants to open each one in a graphics program, write down the dimensions, and type them into the HTML by hand. I needed a way to do this automatically.
The GIF specification puts the logical screen dimensions immediately after the six-byte header. These describe the canvas on which the file’s images appear. The first three bytes are the signature (the letters G, I, F). The width is stored at byte offset 6 as a 16-bit little-endian integer, and the height follows at offset 8. Open the file, seek to that position, and read four bytes to get those dimensions.
Here is the complete script, also available as a download:
#!/usr/local/bin/perl
# Program name: gifsize
# Author: Rajiv Pant (Betul)
# Version: 1.0. October 1994.
foreach $gif (@ARGV)
{
($width, $height, $type) = &gifsize ($gif) ;
($type =~ m/GIF/i)
? print "<img src=\"$gif\" width=$width height=$height border=0>\n"
: print "$gif is not a GIF.\n" ;
}
sub gifsize
{
local ($gif) = @_ ;
local ($w, $w2, $h, $h2, $gifwidth, $gifsize, $type) = () ;
open (GIF, $gif) ; read (GIF, $type, 3) ;
seek (GIF, 6, 0) ; read (GIF, $w, 1) ;
read (GIF, $w2, 1) ;
$width = ord ($w) + ord ($w2) * 256 ;
read (GIF, $h, 1) ; read (GIF, $h2, 1) ;
$height = ord ($h) + ord ($h2) * 256 ;
close (GIF) ;
return ($width, $height, $type) ;
} # end of sub gifsize
You run it like perl gifsize.pl logo.gif masthead.gif and it outputs ready-to-paste HTML:
<img src="logo.gif" width=200 height=50 border=0>
<img src="masthead.gif" width=600 height=80 border=0>
The subroutine reads the fields, then the command-line loop checks whether the first three bytes match GIF. That rejects other prefixes, but it does not validate a complete GIF: a damaged file beginning with those letters can still produce dimensions. Check the results of open, seek and read, and use binary mode on systems that distinguish text and binary files.
To call gifsize from other scripts, put the subroutine in a library file without the command-line loop and end that file with 1;, so Perl’s require receives a true return value. I use it in our publishing system at Philadelphia Newspapers to generate img tags as part of the page-building process. The pages are assembled from templates, and the image tags get their dimensions filled in automatically.
Splitting files for floppy disks uses the same byte-oriented approach. Reading binary file headers directly is a useful technique. The GIF spec is public, the header layout is simple, and Perl's read, seek, and ord functions make it straightforward. No external libraries needed.