PHP: Generate a Thumbnail from a JPG, PNG or GIF Image File Programming 28 JAN 2011

green php elephants - elephpantsWith PHP’s built in access to the decent GD graphics library, generating a thumbnail image from a larger photo turns out to be pretty simple to achieve. Below is a function you can use to create a thumbnail image from either a JPG, PNG or GIF source image.

To use, simply supply the file path to the source image as well as the desired width (though if not given it will be defaulted to 180 pixels wide). The height of the thumbnail is automatically generated so as to keep aspect ration the same.

The function is question:

function createThumbnail($pathToImage, $thumbWidth = 180) {
    $result = 'Failed';
    if (is_file($pathToImage)) {
        $info = pathinfo($pathToImage);

        $extension = strtolower($info['extension']);
        if (in_array($extension, array('jpg', 'jpeg', 'png', 'gif'))) {

            switch ($extension) {
                case 'jpg':
                    $img = imagecreatefromjpeg("{$pathToImage}");
                case 'jpeg':
                    $img = imagecreatefromjpeg("{$pathToImage}");
                case 'png':
                    $img = imagecreatefrompng("{$pathToImage}");
                case 'gif':
                    $img = imagecreatefromgif("{$pathToImage}");
                    $img = imagecreatefromjpeg("{$pathToImage}");
            // load image and get image size

            $width = imagesx($img);
            $height = imagesy($img);

            // calculate thumbnail size
            $new_width = $thumbWidth;
            $new_height = floor($height * ( $thumbWidth / $width ));

            // create a new temporary image
            $tmp_img = imagecreatetruecolor($new_width, $new_height);

            // copy and resize old image into new image
            imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                $pathToImage = $pathToImage . '.thumb.' . $extension;
            // save thumbnail into a file
            imagejpeg($tmp_img, "{$pathToImage}");
            $result = $pathToImage;
        } else {
            $result = 'Failed|Not an accepted image type (JPG, PNG, GIF).';
    } else {
        $result = 'Failed|Image file does not exist.';
    return $result;

//calling the function
$result = explode('|',createThumbnail($sourceImagePath, 180));
            if ($result[0] != 'Failed'){
                header('Location: /thumbnails/' . basename($result[0]));
            } else {
                header('Location: error.gif');

As you can see, the function above returns a string, with the string containing ‘Failed’ if the thumbnail generation has failed for some reason, otherwise returning the path to the generated thumbnail image.


Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • Excellent function, one small thing I noticed was couldn’t the switch statement combine the three cases where imagecreatefromjpeg() is the result, I think it would make the code more readable and save some space. Probably just personal preference!

    Great blog by the way, I have subscribed.

  • Mario Alejandro Gonzales Flore

    Hi Craig,

    I am peruvian web developer, thank you for share createThumbnail function, i add this lines:

    // create a new temporary image

    $tmp_img = imagecreatetruecolor($new_width, $new_height);

    if ($extension == “png” || $extension == “gif” ){

    imagealphablending($tmp_img, false);

    imagesavealpha($tmp_img, true);

    imagealphablending($img, true);


    // copy and resize old image into new image

    imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    $fichero = strtolower($info[‘basename’]);

    $fichero_t = explode( $fichero, $pathToImage);

    $directory = $fichero_t[0];

    $pathToImage = $directory . ‘thumb.’ .strtolower($info[‘filename’]).”.”. $extension;

    // save thumbnail into a file

    if ($extension == “png”){

    imagepng($tmp_img, “{$pathToImage}”);

    }else if ($extension == “gif”)


    imagegif($tmp_img, “{$pathToImage}”);

    } else{

    imagejpeg($tmp_img, “{$pathToImage}”);


    generating thumbnail in png transparent and gif

    Best Regards

  • Mark Trotier

    Thanks so much, this is exactly what this back end front end illiterate programmer needed.

    • Cool, glad it still worked for you. I’m sure there are a lot better, more modern ways of doing this these days though.

  • stefano

    Hi Craig, thank you for the snippet.
    I suggest you to replace imagecopyresized with imagecopyresampled because the latter function produces very better results.