Create Image Thumbnails Using PHP

By  on  

I create a lot of photo galleries for my customers. A website is meant to be a marketing tool and what better way to market your product than showing numerous pictures of the product? One issue that comes up often is that the customer doesn't have a means for creating their own thumbnails. That problem is compounded by the fact that they don't want to pay me to create them. The compromise is the PHP thumbnail generation function I created.

The PHP

function make_thumb($src, $dest, $desired_width) {

	/* read the source image */
	$source_image = imagecreatefromjpeg($src);
	$width = imagesx($source_image);
	$height = imagesy($source_image);
	
	/* find the "desired height" of this thumbnail, relative to the desired width  */
	$desired_height = floor($height * ($desired_width / $width));
	
	/* create a new, "virtual" image */
	$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
	
	/* copy source image at a resized size */
	imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
	
	/* create the physical thumbnail image to its destination */
	imagejpeg($virtual_image, $dest);
}

The above code uses the PHP GD2 library functionality. The only drawback to using PHP for image creation is that the thumbnails don't look as good as thumbnails created in Photoshop or GIMP.

Would you have use for this? Suggestions? Share them!

Recent Features

Incredible Demos

  • By
    CSS pointer-events

    The responsibilities taken on by CSS seems to be increasingly blurring with JavaScript. Consider the -webkit-touch-callout CSS property, which prevents iOS's link dialog menu when you tap and hold a clickable element. The pointer-events property is even more JavaScript-like, preventing: click actions from doing...

  • By
    Comment Preview Using MooTools

    Comment previewing is an awesome addition to any blog. I've seen really simple comment previewing and some really complex comment previewing. The following is a tutorial on creating very basic comment previewing using MooTools. The XHTML You can set up your XHTML any way you'd like.

Discussion

  1. daniele

    You can use a quality parameter in the imagejpeg function!
    I always set to 100% and it seems working quite good… don’t forget it’s a thumb :)

  2. Miguel Palazzo

    There are many ways to do this David :) It is useful if you’re having a CMS or a proper frontend module to upload certain amount of photos and such to create its thumbnail. Best thing about GD2 it’s well, you can do almost everything on an image w/o using Photoshop or GIMP, worst thing is… I dunno you guys but, size does get increased, no compression methods i guess!

  3. Fabian Beiner

    I prefer ImageMagick or GraphicsMagick over GD.

  4. I agree with Danielle that you should include the quality parameter. I generally use 83 for any resizing I do. Why 83? It works out to be about equal (in image quality and filesize) to Photoshop’s Save For Web using JPG at 60 quality. Using 100 at quality works even better if you’re not worried about file size or load time with lots of thumbnails.

  5. As far as I have seen, imagecopyresampled gives far better results than imagecopyresized, altough it takes considerately more processing time.

  6. Am I right in thinking this script creates a physical file for the thumbnail? I’ve always generated them on the fly using a header directive to make the browser render the PHP file as an image.

  7. Fabian Beiner

    Yes, but generating them once is the better choice.

  8. @Lewis: I agree with Fabian.

    • Didier

      a step further to have use of it as asked David, how do you see the way to create a slideshow made with thumbnails from sites such as we can see on Chrome?

  9. As good as it feels to code your own functions, it’s good to know that there’s someone who’s gone to great lengths to code a spectacular class.
    phpThumb (phpthumb.sourceforge.net) is fantastic, easy to implement and very flexible.

  10. I guess on large scale sites creating a thumbnail file makes a lot of sense, even if it is one more thing to keep track off (in terms of CRUD).

    My one concern is if the desired size of thumbnail changes. For example on one of the sites I developed some of the same image files are displayed on different pages at different sizes. For example, I have one gallery system that shows all the images in that gallery at 120px width. On another page random images from that gallery are shown at 400px. At the moment there is one copy of the file on the server and the iamges are resized depending on the requested page.

    Should I create thumbnail files for use in the gallery and generate the random image on the fly, or should I look at creating a third set of images scaled to 400px?

  11. Thank you man! Nice piece of code! :)

  12. Steve

    I have seen “convert” used from ImageMagick with some success. The resulting image is pretty clean..

  13. In the past I was using phpthumb. But nowadays my host server disabled popen and system function, which causing the phpthumb script cannot working properly.

    This might be a solution for me.
    Thank’s

  14. hamideh

    @Fabian Beiner: But The ImageMagick has problem with Safe_mode.It requiress this option to be off which is not secure.

  15. @Fabian Beiner: But The ImageMagick has problem with Safe_mode.It requiress this option to be off which is not secure.

    @Fabian Beiner:

  16. If you want to create thumbnail images from a directory of folders, to a thumb folder, use this thumbnail generator script:

    http://bgallz.org/270/php-create-thumbnail-images/

    This one works well too, doesn’t overwrite.

  17. Didier

    And if you want to create thumbnails from a collection of urls ?

  18. crivion

    a solution to improve would be to either give a 4th param for the image type or auto-detect like gif,jpg,png

  19. karthi

    Hello use this

    its so simple,if u have any queries mail at karthid@in.com

    $ffmpeg = “ffmpeg Installed path”

    $flvfile = “source video file with root path”

    $png_path ” “Destination video file with root path and file type”

    exec(“$ffmpeg -y -i $flvfile -vframes 1 -ss 00:01:60 -an -vcodec png -f rawvideo -s 110×90 $png_path”);

    all the best….

  20. Didier

    Do you think it is possible to create a thumbnail of a web page with PHP ?

    (for your info, actually I use a kind of C++ langage and ActiveX to create thumbnails of web pages, then send the thumbnails by FTP on the server and finally read them on the server with mootools/PHP … nothing very brilliant today)

  21. Where do you specify quality in this code?

  22. Hi guys!

    No matter what I do, the image is garbled and I can’t decode it either. Any ideas?

  23. Maaz

    But this code is only for jpeg. How to handle other image types ?

  24. tryu

    drthyutjuygfjityf

  25. I dont think we can create thumbnail with php.

  26. RedHot

    I suggest you add the following code after :

     $desired_height = floor($height*($desired_width/$width));

    and the code is :

    /* make sure that dimensions width related to height are within range and vice versa */
    if(($desired_height > 10* $desired_width) or ($desired_width > 10* $desired_height)){
      return false;
    }
    

    otherwise if the dimensions are not logically proportional you will get the error saying :
    Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in ….

  27. Agim Allkanjari

    Here is a more improved version of the function.

    function create_thumb($src,$dest,$desired_width = false, $desired_height = false)
    {
        /*If no dimenstion for thumbnail given, return false */
        if (!$desired_height&&!$desired_width) return false;
        $fparts = pathinfo($src);
        $ext = strtolower($fparts['extension']);
        /* if its not an image return false */
        if (!in_array($ext,array('gif','jpg','png','jpeg'))) return false;
    
        /* read the source image */
        if ($ext == 'gif')
            $resource = imagecreatefromgif($src);
        else if ($ext == 'png')
            $resource = imagecreatefrompng($src);
        else if ($ext == 'jpg' || $ext == 'jpeg')
            $resource = imagecreatefromjpeg($src);
        
        $width  = imagesx($source_image);
        $height = imagesy($source_image);
        /* find the "desired height" or "desired width" of this thumbnail, relative to each other, if one of them is not given  */
        if(!$desired_height) $desired_height = floor($height*($desired_width/$width));
        if(!$desired_width)  $desired_width  = floor($width*($desired_height/$height));
      
        /* create a new, "virtual" image */
        $virtual_image = imagecreatetruecolor($desired_width,$desired_height);
      
        /* copy source image at a resized size */
        imagecopyresized($virtual_image,$resource,0,0,0,0,$desired_width,$desired_height,$width,$height);
        
        /* create the physical thumbnail image to its destination */
        /* Use correct function based on the desired image type from $dest thumbnail source */
        $fparts = pathinfo($dest);
        $ext = strtolower($fparts['extension']);
        /* if dest is not an image type, default to jpg */
        if (!in_array($ext,array('gif','jpg','png','jpeg'))) $ext = 'jpg';
        $dest = $fparts['dirname'].'/'.$fparts['filename'].'.'.$ext;
        
        if ($ext == 'gif')
            imagegif($virtual_image,$dest);
        else if ($ext == 'png')
            imagepng($virtual_image,$dest,1);
        else if ($ext == 'jpg' || $ext == 'jpeg')
            imagejpeg($virtual_image,$dest,100);
        
        return array(
            'width'     => $width,
            'height'    => $height,
            'new_width' => $desired_width,
            'new_height'=> $desired_height,
            'dest'      => $dest
        );
    }
    
    • Terrific, just a little correction, this:

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

      should be:

      $width  = imagesx($resource);
      $height = imagesy($resource);
      
  28. Chris Cachor

    One very large important change to this script would be to change the function imagecopyresized to imagecopyresampled. The pixels will be resampled properly so you don’t get that garbled image. It works really quite well :D

  29. working on this task
    would like to remind about images with wrong extension,
    found 1 way to check
    http://www.php.net/manual/en/function.exif-imagetype.php

    want to add this check to Agim Allkanjari script

    dont promise to share :)

  30. Thanks man!!! just what i wanted!! wasted much time creating thumbnails with gimp and photoshop, my work has now reduced greatly..will use it to create thumbnails for wallpapers for my website

    http://www.joseblog.netau.net/wallpapers

  31. JeffreySundays

    ummm…sorry about the formatting of my post (forgot the code closing bracket, can’t edit or delete it:

    Just curious where to stick the 100 quality?

    Would it be here?

    /* create the physical thumbnail image to its destination */
     imagejpeg($virtual_image, $dest,100); 
    

    I also combined this with another script I found, which allows me to post all the images and thumbnails using a while loop so all I need to do is upload the images in the directory & it automatically creates the gallery using just the one echo:

    $file) {
    		$index++;
    		$thumbnail_image = $thumbs_dir.$file;
    			if(!file_exists($thumbnail_image)) {
    			$extension = get_file_extension($thumbnail_image);
    				if($extension) {
    				make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width);
    				}
    			}
    				echo '';
    	}
    
    }
    
    ?>
    
  32. sudha

    i need the example code for creating thumbnail while uploading image using php. the image was not good to look. help

  33. For all looking at how to set the quality, you do it like this

    $quality = 80; // or any desired integer between 1-100
    imagejpeg($virtual_image, $dest, $quality);
    
  34. Shruti

    Dear David,
    I want to create thumbs of images but with specific image name as well. I have downloaded a script from this site: http://ashishrevar.com/2012/10/create-thumbnails-using-php-script/

    I am using wordpress plugin next-gen gallery so, I want to resize images with predefined dimensions and filename(a pattern given by plugin).

    Can you please help me for the same.

    Here is the code that I have copied from the aforesaid site.

  35. Create thumbnail image by php
    When we upload large size images on server. Uploaded large images take more time to load on webpage, so we need to show small size images on our webpage. Image thumbnail is a solution to generate uploaded image’s thumbnail to show required size images on our website.
    http://codelibrary.googleplus.co.in/create-thumbnail-image-by-php/

  36. Hi,
    i created a php class for thumbnail. It’s very easy.

    you can download from this link : https://github.com/selahattinunlu/createThumbnail.class

    Using Manual:

    extensionControl();
    

    Control: upload

    $ct->isUpload();
    
    $ct->newName('new_image.jpg');
    
    $ct->moveUpload('upload/');
    
    $ct->create_thumbnail( 'upload/thumb/', 'thumb.jpg', 300, 300 );
    
    $ct->create_thumbnail( 'upload/thumb/', 'thumb2.jpg', 100, 100 );
    

    Result:

    $ct->result('Upload is succesful');
    
  37. yubraj pokharel

    thanks lot

  38. Elavarasan T

    i have some error like this,
    Message: imagejpeg(http://localhost/ots-tc/trunk/code/hive_tm/attachments/thumb/): failed to open stream: HTTP wrapper does not support writeable connections
    kindly help me..

  39. I am using this on IIS Server but its not working. I have bundled (2.0 compatible) enabled. Its giving blank screen. so can you help me please?

  40. yes this is a simple way of creating thumbnails using GD2 library functionality.

  41. tk

    This works for me for gif,jpg,png

    // thumb nail creation 
    function make_thumb($src, $dest, $desired_width) {
    	/* read the source image */
                          $image_Type = '';
    	$source_imageJpg = imagecreatefromjpeg($src);
                         $source_imagePng = imagecreatefrompng($src);
                          $source_imageGif = imagecreatefromgif($src);
                         if($source_imageJpg){
                              $source_image = $source_imageJpg;
                              $image_Type ='jpg';
                          }else if($source_imagePng){
                              $source_image = $source_imagePng;
                               $image_Type =  'png';
                          }else if($source_imageGif){
                              $source_image = $source_imageGif;
                               $image_Type = 'gif';
                          }
    	$width = imagesx($source_image);
    	$height = imagesy($source_image);
    	
    	/* find the "desired height" of this thumbnail, relative to the desired width  */
    	$desired_height = floor($height * ($desired_width / $width));
    	/* create a new, "virtual" image */
    	$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
    	/* copy source image at a resized size */
    	imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
    	/* create the physical thumbnail image to its destination */
    	 if($image_Type =='jpg'){
               imagejpeg($virtual_image,$dest,80);
            }else if($image_Type == 'png'){
               imagepng($virtual_image,$dest,1);
            }else if($image_Type == 'gif'){
                imagegif($virtual_image,$dest);
            }
      }
     make_thumb($tempFile,$thumbTargetFile,'120');    
    
  42. TiTAN

    Hi
    I use this function, its very good thank you, But I have a problem , When images number is near 1000 it does not work and break, log on apache:

    [Tue Nov 26 18:48:39.271267 2019] [php7:error] [pid 25563] [client 213.233.171.85:38342] PHP Fatal error: Maximum execution time of 30 seconds exceeded in /var/www/html/config.php on line 162, referer: http://37.191.64.67:1894/report.php

    line 162 i imagecopyresampled

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!