Home » Tech News » Lifehacker » How to Create Thumbnail Images in PHP?

How to Create Thumbnail Images in PHP?


Many times your site needs images to be uploaded, maybe for display with submitted content, then you have to make sure that the images displayed should be of a suitable size. If a user uploads a particularly large image, it may destroy the layout of the page when it is displayed.

Thumbnail images guarantee you that the images displayed will never exceed certain height and width values. Creating a basic thumbnail is a five-stage process:

1. Load the source image into a PHP variable.

2. Determine the height and width of the original image.

3. Create a blank thumbnail image of the correct size.

4. Copy the original image to the blank thumbnail.

5. Display the thumbnail using the correct content type.

EXAMPLE: Suppose we have to create a thumbnail from a photo in JPEG format. First of all, we specify the path to the source image as well as our desired width and height in pixels:

$sourceImage = ‘SAMPLE_IMAGES/scenery.jpg’;
$thumbWidth = 200;
$thumbHeight = 200;

Next, we use imagecreatefromjpeg to load an image from the file system into a PHP variable:$original. The getimagesize function returns the width and height of the image.

$original = imagecreatefromjpeg($sourceImage);
$dims = getimagesize($sourceImage);

Then we use the imagecreatetruecolor function to create a blank image into which the thumbnail image will be placed: $thumb = imagecreatetruecolor($thumbWidth,$thumbHeight);

There should be a code for the point at which the thumbnail image is actually created from the original:

imagecopyresampled( $thumb, $original, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $dims[0], $dims[1] );

At last, after we have sent the correct content type header, we’ll use imagejpeg to output the completed thumbnail:

header( “Content-type: image/jpeg” );
imagejpeg( $thumb );



Leave a Reply

Your email address will not be published. Required fields are marked *


|Account Recovery|How to Recover password|Weightloss Product Reviews