Important alert: (current site time 12/22/2014 8:06:35 PM EDT)
 

article

Thumbnails in PHP

Email
Submitted on: 7/21/2003 12:52:29 PM
By: Michael Bailey  
Level: Beginner
User Rating: By 9 Users
Compatibility: PHP 4.0
Views: 36331
author picture
(About the author)
 
     Learn how to use the PHP GD extension to create thumbnails from your normal images on the fly.

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
  1. You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
				

Introduction

Depending upon how it's done, displaying a page of thumbnail images can be very cumbersome. Allowing the browser to resize images requires the client browser to download the entire, full-size image, then clumsily resize the image to a specified size. This causes the page to load very slowly and creates unavoidable distortion in the resulting images. The other option is to make separate thumbnail images for each individual image. This is fine if you only plan to display a few images, but becomes unrealistic on a large scale or a site involving dynamic images. Fortunately there are ways around these problems using the GD library in PHP.

This tutorial will outline how to write a PHP script to create thumbnail images on the fly. Since this requires the GD library, you will need an installation of PHP with at least GD 2.0.1 enabled (you can use older versions with a slight change which I will explain).

The script we will be writing receives one parameter on the query string which corresponds to the relative path of the full-size image. This address is to be placed as the src field of an image tag. An example image tag might look like this: <img src="/thumbnail.php?dir/image.png">. With no further ado let us procede to the source code.

Source Code

# Constants
define(IMAGE_BASE'/var/www/html/mbailey/images');
define(MAX_WIDTH150);
define(MAX_HEIGHT150);

# Get image location
$image_file str_replace('..'''$_SERVER['QUERY_STRING']);
$image_path IMAGE_BASE "/$image_file";

# Load image
$img null;
$ext strtolower(end(explode('.'$image_path)));
if (
$ext == 'jpg' || $ext == 'jpeg') {
    
$img = @imagecreatefromjpeg($image_path);
} else if (
$ext == 'png') {
    
$img = @imagecreatefrompng($image_path);
# Only if your version of GD includes GIF support
} else if ($ext == 'gif') {
    
$img = @imagecreatefrompng($image_path);
}

# If an image was successfully loaded, test the image for size
if ($img) {

    
# Get image size and scale ratio
    
$width imagesx($img);
    
$height imagesy($img);
    
$scale min(MAX_WIDTH/$widthMAX_HEIGHT/$height);

    
# If the image is larger than the max shrink it
    
if ($scale 1) {
        
$new_width floor($scale*$width);
        
$new_height floor($scale*$height);

        
# Create a new temporary image
        
$tmp_img imagecreatetruecolor($new_width$new_height);

        
# Copy and resize old image into new image
        
imagecopyresized($tmp_img$img0000
                         
$new_width$new_height$width$height);
        
imagedestroy($img);
        
$img $tmp_img;        
    }    
}

# Create error image if necessary
if (!$img) {
    
$img imagecreate(MAX_WIDTHMAX_HEIGHT);
    
imagecolorallocate($img,0,0,0);
    
$c imagecolorallocate($img,70,70,70);
    
imageline($img,0,0,MAX_WIDTH,MAX_HEIGHT,$c2);
    
imageline($img,MAX_WIDTH,0,0,MAX_HEIGHT,$c2);
}

# Display the image
header("Content-type: image/jpeg");
imagejpeg($img);

Explanation

We'll now proceed through the script and explain each block in excruciating detail. I hope you have caffeine ready, you may need it.

# Constants
define(IMAGE_BASE'/var/www/html/mbailey/images');
define(MAX_WIDTH150);
define(MAX_HEIGHT150);

First we should define a few constants. IMAGE_BASE points to the directory from which images are to be served. Only images in or under this directory are available. MAX_WIDTH and MAX_HEIGHT specify the maximum size to which images will be shrunk. If an image is already smaller than these sizes, it is returned without modifications. Proportions are also retained so that if the width is reduced by a factor of 2, the height will be reduced by that same factor.

# Get image location
$image_file str_replace('..'''$_SERVER['QUERY_STRING']);
$image_path IMAGE_BASE "/$image_file";

# Load image
$img null;
$ext strtolower(end(explode('.'$image_path)));
if (
$ext == 'jpg' || $ext == 'jpeg') {
    
$img = @imagecreatefromjpeg($image_path);
} else if (
$ext == 'png') {
    
$img = @imagecreatefrompng($image_path);
# Only if your version of GD includes GIF support
} else if ($ext == 'gif') {
    
$img = @imagecreatefrompng($image_path);
}

The image location is passed as the entire query string as explained above. To prevent people from accessing images outside of the specified path, the string replace function is used to remove any "..".

The extension is checked to find out what type of image has been requested. GD has a number of different load functions. Each is of the form imageloadfrom[type](). I have included only the three most common image formats, though others can easily be added.

If the extension is unrecognized or the specified file does not exist, $img is left empty. When this occurs, an error is generated (see below). The @ before the load functions suppresses errors so that the user won't be shown a page of garbage.

NOTE: gif support isn't available in the newer versions of GD. If your version of GD does not support gif images, you should probably remove the lines for handling gif images.

# If an image was successfully loaded, test the image for size
if ($img) {

    
# Get image size and scale ratio
    
$width imagesx($img);
    
$height imagesy($img);
    
$scale min(MAX_WIDTH/$widthMAX_HEIGHT/$height);

imagesx() and imagesy() return the width and height of the image respectively. The maximum size of the image is then divided by the actual size of the image. This results in a scaling ratio. This scaling ratio is multiplied by the actual image size in order to give the reduced size. This value is calculated for both the width and height seperately; though the smaller of the two is used. By using the same value for both width and height, we preserve the correct proportions.

# If the image is larger than the max shrink it
    
if ($scale 1) {
        
$new_width floor($scale*$width);
        
$new_height floor($scale*$height);

        
# Create a new temporary image
        
$tmp_img imagecreatetruecolor($new_width$new_height);

        
# Copy and resize old image into new image
        
imagecopyresized($tmp_img$img0000,
                         
$new_width$new_height$width$height);
        
imagedestroy($img);
        
$img $tmp_img;
    }
}

If the scale ratio is greater than or equal to 1 the image does not need to be modified in any way. Otherwise, the image must be reduced in size by that value. The new image size is generated by multiplying the scale by the current size.

Using these new dimensions a buffer image is created using imagecreatetruecolor(). If you are using a GD library prior to 2.0, you will need to change this function to imagecreate(). The true color version of this function was added in 2.0 to preserve color integrity when parts of an image are copied, which we are about to do. The older function will still work fine for many images, but high color photos and the like may not maintain the correct colors using the older function.

The original image is then resized into the buffer image. Since we will now be using this new image, we are able to free the original image with imagedestroy(). The buffer image is then renamed to $img.

# Create error image if necessary
if (!$img) {
    
$img imagecreate(MAX_WIDTHMAX_HEIGHT);
    
imagecolorallocate($img,0,0,0);
    
$c imagecolorallocate($img,70,70,70);
    
imageline($img,0,0,MAX_WIDTH,MAX_HEIGHT,$c2);
    
imageline($img,MAX_WIDTH,0,0,MAX_HEIGHT,$c2);
}

As was explained earlier, if the image's extension was unrecognizable, or the file did not exist all together, $img was left empty. If this is the case, we need to generate a place holder image to notify the user that the image they requested was unavailable. We do this by drawing a black box with a gray X through the middle. You may want to make this more explicit, by adding text or even redirecting the browser to a premade image.

# Display the image
header("Content-type: image/jpeg");
imagejpeg($img);

The image is finally displayed to the user in jpeg format.

Conclusion

As you can see, adding on-the-fly generated thumbnails to your website is quite easy to accomplish with GD and PHP. Now if you're anything like me, all you need to do is find something worth displaying on your website. That's the part I can't help you with, sorry.



Other 3 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

8/8/2003 3:00:53 AMMindlessOath

what is GD, and how do i know if my server runs it? will i be able to install it??? i dont have access to system files. does php come with GD? etc... give me more info. sorry noobie about this GD stuff, the code is simple and understanding, just what i have been looking for. :)
(If this comment was disrespectful, please report it.)

 
8/13/2003 8:38:45 AM

This is great... exactly what I needed, simple and efficiŽnt !!! Thx !!!
(If this comment was disrespectful, please report it.)

 
8/13/2003 8:42:44 AM

This is great code... exactly what I needed, simple and efficiŽnt !!! Thx !!!
(If this comment was disrespectful, please report it.)

 
1/11/2004 4:09:01 AMJawish

there is an error in your code..
------------------------------------

# Only if your version of GD includes GIF support
} else if ($ext == 'gif') {
$img = @imagecreatefrompng($image_path);
}
-----------------------------------

shu d
be

-----------------------------------
# Only if your version of GD includes GIF support
} else if ($ext == 'gif') {
$img = @imagecreatefromgif($image_path);
}
-----------------------------------

:)< BR>

(If this comment was disrespectful, please report it.)

 
1/15/2004 12:23:31 PMBurner2G

great code... however.. i ntoiced that if the passed image file has spaces in the name it jsut draws a black image because it cant find it. So rather than rename all your images.. just pass it as a variable... like.. thumb.php?i=image.jpg rather than thumb.php?image.jpg then change it in the thumb.php so that it gets the image name from the variable $i instead of from the $_SERVER['QUERY_STRING']
(If this comment was disrespectful, please report it.)

 
4/28/2004 2:27:30 AM

If you want to control the quality of the image, change...

imagejpeg($img);
to
imagejpeg($img,'',100);
(If this comment was disrespectful, please report it.)

 
9/20/2004 4:06:59 AM

How do i create Categories and add text below each of the images.emal me at khulisom@webmail.co.za
(If this comment was disrespectful, please report it.)

 
11/23/2004 4:50:44 PM

Using this method could you also save a
(If this comment was disrespectful, please report it.)

 
11/23/2004 4:51:41 PM

Using this method could you also save a thumbnail image you create to either the filesystem or a field in a database?
(If this comment was disrespectful, please report it.)

 
2/19/2005 4:55:12 PM

Is it efficient to generate thumbs on the fly? Wouldn't it be better to generate them the first time only and cache them.
(If this comment was disrespectful, please report it.)

 
8/5/2006 7:13:45 PMOsama Alex

Hi, it's really great work, but can your program work with the images stored in a database? like replace the value in "IMAGE_BASE" by value like: "127.0.0.1/image.php?id=1" you understand that? OK, thank you again for your work and I hope I recieve the reply as soon as possible! Thanks!
(If this comment was disrespectful, please report it.)

 
10/7/2006 4:22:11 PMphp guy

Try following free php script. It works with GIF, JPG, JPEG, PNG images. Proportional resize. PHP source code provided for free download.

http://www.zubrag.com/scripts/thumbnail-generator.php

(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.