Page 567 - Beginning PHP 5.3
P. 567
Chapter 17: Generating Images with PHP
$mainWidth = imagesx( $mainImage );
$mainHeight = imagesy( $mainImage );
$thumbWidth = intval( $mainWidth / 4 );
$thumbHeight = intval( $mainHeight / 4 );
$myThumbnail = imagecreatetruecolor( $thumbWidth, $thumbHeight );
imagecopyresampled( $myThumbnail, $mainImage, 0, 0, 0, 0, $thumbWidth,
$thumbHeight, $mainWidth, $mainHeight );
header( “Content-type: image/jpeg” );
imagejpeg( $myThumbnail );
imagedestroy( $myThumbnail );
imagedestroy( $mainImage );
? >
Save the script as thumbnail.php in your document root folder, replacing lucky.jpg in the second line
with an image of your own (saved in the same folder). Run the script by opening its URL in your Web
browser. Figure 17 - 22 shows a sample run.
Here ’ s how the script works. First it opens the image to create the thumbnail for:
$mainImage = imagecreatefromjpeg( “lucky.jpg” );
Next it uses the imagesx() and imagesy() functions to get the width and height of the original image.
You need these to work out the size of the new thumbnail image:
$mainWidth = imagesx( $mainImage );
$mainHeight = imagesy( $mainImage );
In this example, the thumbnail will be a quarter the size of the original image, so the script divides the
original width and height by four to compute the thumbnail dimensions. The resulting values are then
rounded to whole numbers with the intval() function (because you can ’ t work with half - pixels):
$thumbWidth = intval( $mainWidth / 4 );
$thumbHeight = intval( $mainHeight / 4 );
Now the script creates a new blank image to store the thumbnail. Typically you ’ ll be making thumbnails
of photos, so you want an image with a large number of colors. Therefore the script uses the
imagecreatetruecolor() function to create the blank thumbnail image:
$myThumbnail = imagecreatetruecolor( $thumbWidth, $thumbHeight );
Next the script needs to scale down the original image and copy it into the new thumbnail image. Two
functions can do this: imagecopyresized() and imagecopyresampled() . The difference between the
two is that imagecopyresized() is slightly faster, but does not smooth the image at all. If you use
imagecopyresized() to create a thumbnail and then zoom in, you ’ ll see a blocky effect much like that
shown in Figure 17 - 21.
529
9/21/09 2:48:46 PM
c17.indd 529
c17.indd 529 9/21/09 2:48:46 PM