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.


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!

Track.js Error Reporting

Recent Features

  • CSS vs. JS Animation: Which is Faster?

    How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps? This article serves as a point-by-point...

  • From Webcam to Animated GIF: the Secret Behind chat.meatspac.es!

    My team mate Edna Piranha is not only an awesome hacker; she's also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in a bunch of interesting experimental projects...

Incredible Demos

  • CSS Vertical Center with Flexbox

    I'm 31 years old and feel like I've been in the web development game for centuries.  We knew forever that layouts in CSS were a nightmare and we all considered flexbox our savior.  Whether it turns out that way remains to be seen but flexbox does easily...

  • CSS Tooltips

    We all know that you can make shapes with CSS and a single HTML element, as I've covered in my CSS Triangles and CSS Circles posts.  Triangles and circles are fairly simply though, so as CSS advances, we need to stretch the boundaries...


  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.

  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:


    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
  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


  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 */
        /* 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')
        else if ($ext == 'png')
        else if ($ext == 'jpg' || $ext == 'jpeg')
        return array(
            'width'     => $width,
            'height'    => $height,
            'new_width' => $desired_width,
            'new_height'=> $desired_height,
            'dest'      => $dest
  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

    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


  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) {
    		$thumbnail_image = $thumbs_dir.$file;
    			if(!file_exists($thumbnail_image)) {
    			$extension = get_file_extension($thumbnail_image);
    				if($extension) {
    				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.

  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:


    Control: upload

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


    $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.

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

Recently on David Walsh Blog

  • OSCON Portland:  Conference  Discount!

    O'Reilly puts on the best web industry conferences in the world.  These conferences include Fluent Conference, Velocity Conference, and the upcoming OSCON in Portland, Oregon from July 20-24.  Open Source Convention (OSCON) is a conference that focuses specifically on open source developers and the tools and possibilities...

  • Follow Redirects with cURL

    I love playing around with cURL. There's something about loading websites via command line that makes me feel like some type of smug hacker, just like tweeting from command line does. I recently cURL'd the Google homepage and saw the following: I found it weird that Google...

  • Developers Have WordPress, Amateurs Have Squarespace, Professional Designers Have the NEW Webydo!

    Web design platforms have traditionally come in one of two varieties. There are the solutions like WordPress and Drupal that are incredibly powerful, but an understanding of web development and coding is required to be able to use those platforms effectively. On the other side of the...

  • Chris Coyierâs Favorite CodePen Demos II

    Hey everyone! Before we get started, I just want to say it’s damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so...

  • GSAP + SVG For Power Users: Motion Along A Path

    Now that the GreenSock API is picking up steam, there are many tutorials and Getting Started guides out there to provide good introductions to the library, not to mention GreenSock’s own Forum and Documentation. This article isn’t intended for beginners, but rather a...