#--------------------------------------------------
#  画像サイズ取得ライブラリ
#  $Id: imgSz.pl,v 1.1.1.1 2003/09/04 13:26:53 Watson Exp $
#--------------------------------------------------
# 使い方
#   require "imgSz.pl";
#
#   ($width, $height) = &imgSz'getSize('test.jpg');
#       [あるいは]
#   ($width, $height) = &imgSz::getSize('test.png');
#
#   print "$width $height";

package imgSz;

#--------------------------------------------------
sub getSize {
    my($fileName) = @_[0];
    my($buf);
    my $size = -s $fileName;
    open(IN, "$fileName") || return("ERROR");
    binmode(IN);
    read(IN, $buf, $size) || return("ERROR");
    close(IN);

    $fileName =~ /^(.+)\.([^\.]+)$/;
    my $ext = $2;

    if($ext =~ /gif/i) {
	($width, $height) = &szGif($buf);
    } elsif($ext =~ /png/i) {
	($width, $height) = &szPng($buf);
    } elsif($ext =~ /jpg/i) {
	($width, $height) = &szJpeg($buf);
    } else {
	return("ERROR");
    }
    return ($width, $height);
}
#--------------------------------------------------
sub szGif {
    my $buf = @_[0];

    my $width = unpack("v", substr($buf, 6, 2));
    my $height= unpack("v", substr($buf, 8, 2));

    return ($width, $height);
}
#--------------------------------------------------
sub szJpeg {
    my($buf) = @_;
    my($width, $height);

    my($i) = 2;
    my($t, $m, $c, $l);
    while (1) {
	$t = substr($buf, $i, 4); $i += 4;
	($m, $c, $l) = unpack("a a n", $t);
	if ($m ne "\xFF") { $width = $height = 0; last; }
	elsif ((ord($c) >= 0xC0) && (ord($c) <= 0xC3)) {
	    $height = unpack("n", substr($buf, $i+1, 2));
	    $width = unpack("n", substr($buf, $i+3, 2));
	    last;
	} else {
	    $t = substr($buf, $t, ($l - 2)); $i += $l - 2;
	}
    }
    return ($width, $height);
}
#--------------------------------------------------
sub szPng {
    my($buf) = @_[0];

    my $width = unpack("N", substr($buf, 16, 4));
    my $height= unpack("N", substr($buf, 20, 4));

    return ($width, $height);
    
}
#--------------------------------------------------

1;