image map linking to parts of siteSearch Me?What I DidWhat I DoWriting: archived articlesBlog: Glenn's Daily Thoughts

Decoding a GIF image width and height using a perl subroutine

This is a simple perl subroutine that when given a filename of a GIF, returns the width and height in pixels by decoding the information from the first 10 bytes of the GIF file itself.

The statement to include is something like

print "<IMG SRC=\"$filename\" WIDTH=\"" . $$widthref . "\" HEIGHT=\"" . $$heightref . "\">\n";

Here's the subroutine (modified to an elegant trimness by Dan Lewart, 11/98; thanks, Dan!):

#!/usr/bin/perl -w

use strict;

# ($heightref, $widthref) = gifdim($filename);

sub gifdim ($) {
    my $filename = $_[0];

    open(GIF, $filename) || return (undef, undef);
    my $buf = '';
    my $n = read GIF, $buf, 10;
    close GIF;

    return (undef, undef) if $n < 10;
    my ($head, $width, $height) = unpack("A6vv", $buf);
    return (undef, undef) unless $head =~ /^GIF8[79]a/;
    return \($width, $height);