in reply to How can I get an image's height and length without Image::Size()?
I've written a small routine that recognizes some image file formats and returns the width and height. But you're much better off using Image::Size...
# By max.maischein@econsult.de # # Simple recipe to create proper width= and height= attributes # for <IMG> tags sub PNGsize( $ ) { # Returns a 2 element array containing the width and height of t +he image my $Buffer = shift; my ($Width, $Height) = ( undef, undef ); # Assume failure if ($Buffer =~ /IHDR(.{8})/) { # Now save the numbers my $Data = $1; ($Width, $Height) = unpack( "NN", $Data ); } else { print "'$Filename' is no PNG image (or has weird format +)\n"; }; return ($Width, $Height); }; sub GIFsize( $ ) { my $ID; my $bytes = shift; my ($Width, $Height) = (undef, undef); if ($bytes =~ /^GIF8/) { ($ID, $Width, $Height) = unpack( "A6SS", $bytes ); } else { print "imgsize:GIF:No GIF header found\n"; }; return ($Width,$Height); }; sub JPGsize( $ ) { my $buffer = shift; my ($Width, $Height) = (undef, undef); my $SOF = pack("CC", 0xFF, 0xC0 ); if ($buffer =~ /$SOF...(....)/ ) { $buffer = $1; ($Height,$Width) = unpack( "nn", $buffer ); } else { print "imgsize:JPeG:No SOF header found\n"}; return ($Width, $Height); }; sub img { my $Filename = shift; my $alt = shift || ""; my $attributes = shift || ""; my $ID; $alt =~ s/(.+)/ alt=\"$1\" /; my $result; my $absdir; if (!defined( &dirname )) { use File::Basename; }; $absdir = dirname( $inputfile ); my( $absname ) = build_path( $absdir, $Filename ); #print $absname, "\n"; my ($Width, $Height) = (undef, undef); my $SizeFunc = undef; # assume failure my $Buffer = ""; if ( open( IMGFILE, "<" . $absname )) { binmode IMGFILE; read( IMGFILE, $Buffer, 2048 ) or print "Error reading from '$ +absname' : $!\n"; close( IMGFILE ) or print "Error closing '$absname' : $!\n"; } else { print "Error opening '$absname' : $!\n"; $Buffer = undef; }; if (defined( $Buffer )) { if ($Filename =~ /\.gif$/i) { $SizeFunc = \&GIFsize; } elsif ($Filename =~ /\.jpe?g$/i) { $SizeFunc = \&JPGsize; } elsif ($Filename =~ /\.png$/i) { $SizeFunc = \&PNGsize; } else { print "\nUnknown file extension for image : $imagename (ign +ored)"; }; if (defined( $SizeFunc )) { ($Width, $Height) = &{$SizeFunc}( $Buffer ); }; }; $attributes .= ( $Width ? " width=\"$Width\"" : "" ) . ( $Height + ? " height=\"$Height\"" : "" ); $result = "<IMG src=\"$Filename\"" . $alt . $attributes . "> +"; return( $result ); };
|
|---|