Specifications

$height = $size[1];
$x_ratio = $max_width / $width;
$y_ratio = $max_height / $height;
if ( ($width <= $max_width) && ($height <= $max_height) ) {
$tn_width = $width;
$tn_height = $height;
}
else if (($x_ratio * $height) < $max_height) {
$tn_height = ceil($x_ratio * $height);
$tn_width = $max_width;
}
else {
$tn_width = ceil($y_ratio * $width);
$tn_height = $max_height;
}
$src = ImageCreateFromJpeg($image);
$dst = ImageCreate($tn_width,$tn_height);
ImageCopyResized($dst, $src, 0, 0, 0, 0,
$tn_width,$tn_height,$width,$height);
header(“Content-type: image/jpeg”);
ImageJpeg($dst, null, -1);
ImageDestroy($src);
ImageDestroy($dst);
?>
The script takes three parametersthe filename of the image to display, the maximum width,
and the maximum height in pixels. It is not to say that if the maximum size specified is
200×200, the image will be scaled to 200×200. Rather, it will be scaled down in proportion so
that the larger of the width or height is 200 pixels and the other dimension is 200 pixels or
smaller. For instance, a 400×300 image would be reduced to 200×150. This way the propor-
tions of the image will be maintained.
Resizing on-the-fly on the server is a better option than just specifying HEIGHT and WIDTH
attributes to the <IMG SRC> tag. The large, high-resolution image that a writer submitted might
be several megabytes in size; but when scaled to a reasonable size, it could be under 100k.
There is then no need to download the huge file and ask the browser to resize it.
The image manipulation functions are covered in detail in Chapter 19. Here we are using the
ImageCopyResized() function to scale the image on-the-fly to the required size.
Building Practical PHP and MySQL Projects
P
ART V
594
LISTING 26.1 Continued
32 7842 ch26 3/6/01 3:36 PM Page 594