Can I check the dimensions of an image by using Perl?
Printable View
Can I check the dimensions of an image by using Perl?
Hi,
you can write a script like this for gif images
sub gifsize
{ my $f = shift;
open F, $f;
read F, $buf, 6;
return { status => 0, error => "not gif" } if($buf !~ /GIF8[79]a/);
read F, $buf, 4;
($w, $h) = unpack("vv", $buf);
close F;
return { status => 1, size = -s _, width => $w, height => $h };
}
and similar functions for jpg, swf or other formats you care about
Musicman
Do you mind providing a little explanation? Even though I know Perl, but err.......I don't understand what you are writing......:D
The only thing I know is that you're writing a subroutine.....:D
sub gifsize
{ my $f = shift; ## call as $imgdata = gifsize($filename), $f becomes local copy of $filename
open F, $f; ## open that file ... assume its existence has already been tested
binmode F; ## tell windows it is binary file, not required for other systems
read F, $buf, 6; ## read first 6 bytes of file header, should be GIF87a or GIF89a
return { status => 0, error => "not gif" } if($buf !~ /GIF8[79]a/); ## otherwise return "bad" result
read F, $buf, 4; ## read four more binary bytes, these are the image width and height in "vax" byte order
($w, $h) = unpack("vv", $buf); ## returns unpack result as a list
close F; ## done with that file
return { status => 1, width => $w, height => $h }; ## return "good" result as a hash reference
}
I removed the filesize here, because the whole thing would probably by used like
if(-r $imgfile) ## file readable at all
{ $imgdata = gifsize($imgname) if($imgname =~/\.gif$/i);
$imgdata = jpegsize($imgname) if($imgname =~/\.jpe?g$/i);
...
if(defined($imgdata) && $$imgdata{status})
{ ## image could be deciphered
$$imgdata{size} = -s _;
print "$filename is a " . $$imgdata{width} "x" $$imgdata{height} . " image, size " . $$imgdata{size} . " bytes\n";
You could return hashes rather than hash references, like
return ('status', 1, 'width', $w, 'height', $h);
and then access the results as $imgdata{width} rather than $$imgdata{width}
For details of pack / unpack function please use man perl or read the camel book
Musicman