The most effective method of decreasing the size of an image is to create smaller versions, or thumbnails, of the original. You may easily create thumbnails with the LIB_thumbnail
library, which you can download from this book’s website. To use this library, you will have to verify that your configuration uses the gd (revision 2.0 or higher) graphics module.[28] The script in Example 7-12 demonstrates how to use LIB_thumbnail
to create a miniature version of a larger image. The PHP sections of this script appear in bold.
Example 7-12. Demonstration of how LIB_thumbnail
may create a thumbnailed image
# Demonstration of LIB_thumbnail.php # Include libraries include("LIB_http.php"); include("LIB_thumbnail.php"); # Get image from the Internet $target = "http://www.schrenk.com/north_beach.jpg"; $ref = ""; $method = "GET"; $data_array = ""; $image = http_get($target, $ref, $method, $data_array, EXCL_HEAD); # Store captured image file to local hard drive $handle = fopen("test.jpg", "w"); fputs($handle, $image['FILE']); fclose($handle); # Create thumbnail image from image that was just stored locally $org_file = "test.jpg"; $new_file_name = "thumbnail.jpg"; # Set the maximum width and height of the thumbnailed image $max_width = 90; $max_height= 90; # Create the thumbnailed image create_thumbnail($org_file, $new_file_name, $max_width, $max_height); ?> Full-size image<br> <img src="test.jpg"> <p> Thumbnail image<br> <img src="thumbnail.jpg">
The script in Example 7-12 fetches an image from the Internet, writes a copy of the original to a local file, defines the maximum dimensions of the thumbnail, creates the thumbnail, and finally displays both the original image and the thumbnail image.
The product of running the script in Example 7-12 is shown in Figure 7-8.
The thumbnailed image shown in Figure 7-8 consumes roughly 30 percent as much space as the original file. If the original file was larger or the specification for the thumbnailed image was smaller, the savings would be even greater.
[28] If the gd module is not installed in your configuration, please reference http://www.php.net/manual/en/ref.image.php for further instructions.