65.9K
CodeProject is changing. Read more.
Home

Thumbnail images in PHP

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.36/5 (6 votes)

Aug 18, 2008

CPOL
viewsIcon

35124

downloadIcon

722

Creating thumbnail images using PHP.

Introduction

At times, we need to change image sizes. We will see here how we can do that using PHP.

Using the code

This is the main function we will use:

function thumbnail_image($original_file_path, $new_width, $new_height, $save_path="")

Parameters:

  • $original_file_path: Path of the original image
  • $new_width: Width of the thumbnail image
  • $new_height: Height of the thumbnail image
  • $save_path: Path of the created thumbnail (if you skip this, the thumbnail image will be saved in the original image's folder with a thumbnail.* file name)

Returns:

This function is void thus returns nothing.

The following function creates the thumbnail image in the sample:

<?php
require_once("thumbnail.php");
thumbnail_image("source.jpg","320", "200", "");
?>

The above sample creates thumbnail.jpg as a 320*200 image inside source.jpg.

How does it work

I get the image information using the getimagesize PHP function.

$imgInfo = getimagesize($original_file_path);
$imgExtension = ""; //extension of original image

switch ($imgInfo[2])
{
    case 1:
        $imgExtension = '.gif';
        break;

    case 2:
        $imgExtension = '.jpg';
        break;

    case 3:
        $imgExtension = '.png';
        break;
}

If $save_path equals "" then the thumbnail file will be "thumbnail".$imgExtension.

if ($save_path=="") $save_path = "thumbnail".$imgExtension ;

Here is how to get the width and height of the original image and creating an image object for the thumbnail image:

// Get new dimensions
list($width, $height) = getimagesize($original_file_path);

// Resample
$imageResample = imagecreatetruecolor($new_width, $new_height);

if ( $imgExtension == ".jpg" )
{
    $image = imagecreatefromjpeg($original_file_path);
}
else if ( $imgExtension == ".gif" )
{
    $image = imagecreatefromgif($original_file_path);
}
else if ( $imgExtension == ".png" )
{
    $image = imagecreatefrompng($original_file_path);
}

imagecopyresampled($imageResample, $image, 0, 0, 0, 0, $new_width,
                   $new_height, $width, $height);

Lastly, create the thumbnail image and save it:

if ( $imgExtension == ".jpg" )
{
    imagejpeg($imageResample, $save_path);
}
else if ( $imgExtension == ".gif" )
{
    imagegif($imageResample, $save_path);
}
else if ( $imgExtension == ".png" )
{
    imagepng($imageResample, $save_path);
}