Getting image size

Top Japanese page




Overview

Obtaining image size using GD. This methodology is used in most of my CGIs which use images.

Flow

  1. Make an object from a image file
  2. Obtain image size(geometry) from the object

A sample code

 use GD;
 
 my $im;
 $im =~ /\.jpe?g$/i and $im = GD::Image->newFromJpeg($imagefile);
 $im =~ /\.gif$/i   and $im = GD::Image->newFromGif($imagefile);
 $im =~ /\.png$/i   and $im = GD::Image->newFromPng($imagefile);
 $im =~ /\.xbm$/i   and $im = GD::Image->newFromxbm($imagefile);
 $im =~ /\.gd$/i    and $im = GD::Image->newFromgd($imagefile);
 $im =~ /\.gd2$/i   and $im = GD::Image->newFromgd2($imagefile);
 $im =~ /\.xpm$/i   and $im = GD::Image->newFromxpm($imagefile);
 
 my ($width, $height) = $im->getBounds();

Description of the code

 use GD;

Load GD.

 my $im;
 $im =~ /\.jpe?g$/i and $im = GD::Image->newFromJpeg($image);
 $im =~ /\.gif$/i   and $im = GD::Image->newFromGif($image);
 $im =~ /\.png$/i   and $im = GD::Image->newFromPng($image);
 $im =~ /\.xbm$/i   and $im = GD::Image->newFromxbm($image);
 $im =~ /\.gd$/i    and $im = GD::Image->newFromgd($image);
 $im =~ /\.gd2$/i   and $im = GD::Image->newFromgd2($image);
 $im =~ /\.xpm$/i   and $im = GD::Image->newFromxpm($image);

$image contains an image file. Based on the extention, select a constracter method which load an image file and generate an object.

Old versions of GD do not support newFromGif. And if the extention and actual image format is different, the GD reports an error. If the image file's size is 0, the GD also reports an error. These errors are fatal and script itself stops working. The error cause could be found from the server log file and must be fix the cause.

 my ($width, $height) = $im->getBounds();

Get the image size by getBound method. The widht is put into $width, the heigh is put into $height.