PHPRO.ORG

As a compliment to the amazing iMagick extension which allows an easy method to create thumbnails from images, this example shows how to create a thumbnail image using the GD library that is bundled with PHP. The script also takes into account the dimensions of the image and maintains the original aspect ratio to avoid any distortion.

In this example, the image is a JPG but other formats can be used in the same manner with imageCreateFromGif and imageGif etc. Note the use of imageCopyResampled to give better image quality than imageCopyResized.


<?php

    error_reporting
(E_ALL);

    
$width 80;

    
/*** the image file to thumbnail ***/
    
$image 'spork.jpg';

    if(!
file_exists($image))
    {
        echo 
'No file found';
    }
    else
    {
        
/*** image info ***/
        
list($width_orig$height_orig$image_type) = getimagesize($image);

        
/*** check for a supported image type ***/
        
if($image_type !== 2)
        {
            echo 
'invalid image';
        }
        else
        {
            
/*** thumb image name ***/
            
$thumb 'thumb.jpg';

            
/*** maintain aspect ratio ***/
            
$height = (int) (($width $width_orig) * $height_orig);

            
/*** resample the image ***/
            
$image_p imagecreatetruecolor($width$height);
            
$image imageCreateFromJpeg($image);
            
imagecopyresampled($image_p$image0000$width$height$width_orig$height_orig);

            
/*** write the file to disc ***/
            
if(!is_writeable(dirname($thumb)))
            {
                echo 
'unable to write image in ' dirname($thumb);
            }
            else
            {
                
imageJpeg($image_p$thumb100);
            }
        }
    }
?>

Demonstration

Original

spork

Thumbnail

thumbnail