A little about me

pascal Hi, my name is Pascal and I am a SAP & Supply Chain specialist. I work for PLAUT and I do things others can't.

This blog only contains my personal views, thoughts and opinions. It is not endorsed by my employer nor does it constitute any official communication of PLAUT. You can contact me via email at pascal[at]renet-web.net or use the contact form that you will find by following the 'Contact' link and you can follow me on twitter here.

Click me

Nice gallery thumbnails in PHP

Posted on September 28, 2005 | Category: PHP

Some time ago when I first started publishing photos to the web I used a php package called WihPhoto which used to be available form wihsy.com. I say ‘used to be’ because that site now only displays a dull ‘currently offline’ page. I used a very early version of it and I believe that follow-on versions got a lot of flack because there was a security hole in them. Anyway, I think that it is a shame that it does no longer seem to be updated as it is a great package.

That said, with time I became more and more demanding in terms of what functionalities I wanted it to have and in terms of integration with the general layout of my site. With no ongoing development I had no choice but to add those functionalities myself.

Amongst the various enhancements that I added to it was the ability to generate square thumbnails and I guess you could say that it was a two step process.

  • 1 – Generate square thumbnails
  • 2 – Get rid of the ‘jags’ in the pictures

In this post I’ll discuss how you can generate square thumbnails using php.

The first reason for which I wanted to generate square thumbnails is because I used to post digital pictures that were both in landscape and portrait mode. The thumbnails generated were just resized versions of the larger pictures – so I ended up with landscape and portrait mode thumbnails. This causes some issues in terms of layout because the width of a portrait mode picture is obviously less than that of landscape mode pictures. This means that your page could have thumbnails arranged as below:

That does not look very nice. With a bit of simple code you could have your page look something like that shown below. I.e you could centre align all you thumbnails. It’s better, but it is not good enough. Also you could have a mix of portrait and landscape mode thumbnails on a line. You layout could look like this.

Everything is nicely centered, but it is not visually appealing. So in came the idea of square thumbnails. What I find great with square thumbnails is that you do not use the complete picture to generate the thumbnails, i.e you call on your visitors’ curiosity to show them part of the picture. Another great advantage of square thumbnails is control: If you generate thumbnails that are 100*100 pixels you know exactly how much space you are going to need if you put 5 of them on a line.

Now to be clear I’m not talking about taking 640*480 picture and resizing it to 100*100 either – we respect the original height to width ratio of the subject.

So here it goes. We’ll start with the picture shown below. The original is a 640*480 picture.

The first step consists of reading the dimensions of the picture and figure out which of the height or width is the smallest dimension.

Depending on which of the two is the smallest dimension I make them both equal and from then on we can work out the square are we’re going to be be working with.

This generates thumbnails that have the same width and height and allows for a layout to look like so:

And here is the code that I use to generate those thumbnails. Basically I use a function because the thumbnail creation process can happen in numerous places, but it’s only coded once. Hope it helps someone out there!

The $ImageTool used is ‘GD’.

function CreateSquareThumb($source,$dest,$border=0) {

    $new_width = 100; //
    $new_height = 100; //
    $sourcedate = 0;
    $destdate = 0;
    global $convert;
    if (file_exists($dest)) {
       clearstatcache();
       $sourceinfo = stat($source);
       $destinfo = stat($dest);
       $sourcedate = $sourceinfo[10];
       $destdate = $destinfo[10];
    }
    if (!file_exists("$dest") or ($sourcedate > $destdate)) {
       global $ImageTool;
       $imgsize = GetImageSize($source);
       $width = $imgsize[0];
       $height = $imgsize[1];

      if ($width > $height) { // If the width is greater than the height it's a horizontal picture
        $xoord = ceil(($width - $height) / 2 );
        $width = $height;      // Then we read a square frame that  equals the width
      } else {
        $yoord = ceil(($height - $width) / 2);
        $height = $width;
      }
         $new_im = ImageCreatetruecolor($new_width,$new_height);
         $im = ImageCreateFromJPEG($source);
         imagecopyresampled($new_im,$im,0,0,$xoord,$yoord,$new_width,$new_height,$width,$height);
         ImageJPEG($new_im,$dest,90);

    }
}

» Filed Under PHP

25 Responses to “Nice gallery thumbnails in PHP”

  1. borgo Says:

    Thats what I was looking for! thanks!

  2. Roman Says:

    Very cool code, it must be cool that you display de complete code.

    Greatings from Mexico!!

  3. Barry Cordingley Says:

    Thanks This will take a image held in root where the script is running and output a thumb_imageName in the same root dir.
    Have fun and thanks for the formula.

    $height):
    $xPos = ceil(($width – $height) / 2 );
    $width = $height;
    break;

    default:
    $yPos = ceil(($height – $width) / 2 );
    $height = $width;
    break;

    }

    $dst = ImageCreateTrueColor($setWidth, $setHeight);

    ImageCopyResampled($dst, $src, 0, 0, $xPos, $yPos, $setWidth, $setHeight, $width, $height);

    $savedFile = “thumb_”.$imgTemp.”" ;

    imagejpeg($dst, $savedFile);

    chmod($savedFile, 0644);

    imagedestroy($dst);
    imagedestroy($src);

    ?>

  4. Barry Cordingley Says:

    OPPS! sorry here it is

    $height):
    $xPos = ceil(($width – $height) / 2 );
    $width = $height;
    break;

    default:
    $yPos = ceil(($height – $width) / 2 );
    $height = $width;
    break;

    }

    $dst = ImageCreateTrueColor($setWidth, $setHeight);

    ImageCopyResampled($dst, $src, 0, 0, $xPos, $yPos, $setWidth, $setHeight, $width, $height);

    $savedFile = “thumb_”.$imgTemp.”" ;

    imagejpeg($dst, $savedFile);

    chmod($savedFile, 0644);

    imagedestroy($dst);
    imagedestroy($src);

    ?>

  5. Barry Cordingley Says:

    $imgTemp = ’112567-45885.jpg’;

    $src = ImageCreateFromJPEG($imgTemp);

    $setWidth = ’100′;
    $setHeight = ’100′;

    $xPos = ”;
    $yPos = ”;

    $width = ImageSx($src);
    $height = ImageSy($src);

    switch ($width){

    case $width == ($width > $height):
    $xPos = ceil(($width – $height) / 2 );
    $width = $height;
    break;

  6. Barry Cordingley Says:

    default:
    $yPos = ceil(($height – $width) / 2 );
    $height = $width;
    break;

    }

    $dst = ImageCreateTrueColor($setWidth, $setHeight);

    ImageCopyResampled($dst, $src, 0, 0, $xPos, $yPos, $setWidth, $setHeight, $width, $height);

    $savedFile = “thumb_”.$imgTemp.”" ;

    imagejpeg($dst, $savedFile);

    chmod($savedFile, 0644);

    imagedestroy($dst);
    imagedestroy($src);

  7. Pascal Says:

    Hello Barry,
    Thanks for your numerous comments.
    I prefer to have a seperate folder for my thumbs. The reason being that I may want to change my script so as to generate a thumbnail with a better quality for example – in which case I just delete the whole content of a folder without asking myself the question of what is a thumbnail and what is not.

  8. Neverwolf Says:

    Wow, I think thats what I’ve been looking for. Thank you so much! (Sorry for my english, I’m from Spain).

  9. Pascal Says:

    Neverworld, your English is very good.
    I’m glad this script helps you.

  10. Buriza Says:

    Thanks dude, saved me the effort of having to think at 2am :)

    thanks!

  11. Nick Says:

    Nice script, but GD is very slow and memory consuming.

    You can do this better with imagik.

  12. lurker Says:

    good script.
    I wondered how to make square thumbnail.
    You are so smart! :)

  13. ebw Says:

    this code is good, but it started to work only after i removed qutes from “$dest”
    (..if (!file_exists(“$dest”)..)
    i don’t know. maybe some specific settings or old version on my server. anyway now it work. thanks!

  14. Klaus Says:

    Thanks a lot; great script and explanation.

  15. acctman Says:

    Thanks for the script. How do I use the script can you provide an example as to how to use the script on an image?

  16. renet@web Says:

    Hey ,
    Thanks for the comment. At the moment I’m a little under the pump, but I’ll get back to you when / if I have time.

  17. acctman Says:

    i figured it out, after including the file
    <?php
    include ‘sqrthumb.php’; // this is the file with the thumb code.
    CreateSquareThumb(“/home/site/public_html/files/9ed7.jpg”, “/home/site/public_html/files/test.jpg”);

    ?.

  18. Dennis Says:

    Thanks for the script! Sweet job.
    Changed it a bit to fit my needs. Now it supports also PNG and GIF and allows to pass a different thumb size; maybe someone can use it:

    $destdate)) {
    global $sourceTool;
    $imgsize = GetImageSize($source);
    $width = $imgsize[0];
    $height = $imgsize[1];

    if ($width > $height) { // If the width is greater than the height it’s a horizontal picture
    $xoord = ceil(($width – $height) / 2 );
    $width = $height; // Then we read a square frame that equals the width
    } else {
    $yoord = ceil(($height – $width) / 2);
    $height = $width;
    }
    $new_im = ImageCreatetruecolor($new_width,$new_height);

    //$im = ImageCreateFromJPEG($source);
    switch($resource['type']) {
    case ‘image/gif’:
    $im = ImageCreateFromGIF($source);
    break;
    case ‘image/jpeg’:
    case ‘image/pjpeg’:
    $im = ImageCreateFromJPEG($source);
    break;
    case ‘image/png’:
    $im = ImageCreateFromPNG($source);
    break;
    default:
    die(“JPG, GIF and PNG only. Please try again“);
    break;

    }

    imagecopyresampled($new_im,$im,0,0,$xoord,$yoord,$new_width,$new_height,$width,$height);

    //ImageJPEG($new_im,$dest,90);
    switch($resource['type']) {

    case ‘image/gif’:
    imagegif($new_im, $dest, 90);
    break;

    case ‘image/jpeg’:
    case ‘image/pjpeg’:
    imagejpeg($new_im, $dest, 90);
    break;

    case ‘image/png’:
    imagepng($new_im, $dest, 0);
    break;

    }

    }
    }
    ?>

  19. Dennis Says:

    PS. the $resource parameter is the original image from $_FILES post data. Also removed the $border parameter.

    Hm somehow the first lines were cut of previous post. Try again first lines only:

    <?php
    function square_thumb($source,$dest,$resource,$size = 100) {

    $new_width = $size;
    $new_height = $size;
    $sourcedate = 0;
    $destdate = 0;
    global $convert;
    if (file_exists($dest)) {

  20. acctman Says:

    how do you keep the image within a certain ratio or use % for the height with a set width

  21. Torriv Says:

    Just what I was looking for. But what if i want it to resize/crop on the fly and not save a new file of the resized image?

  22. a|x Says:

    Thanks for sharing- very useful!!

    It’s worth noting that on some systems, gd function names are case-sensitive.
    For example, on my system
    ‘ImageCreatetruecolor’
    does not work, whereas
    ‘imagecreatetruecolor’
    does. All the other gd functions in your code are the same.

    I’m using a Mac running MacOS 10.5.7, and the entropy build of PHP 5.3.0 with gd 2.0.34 compatible.

    In the PHP manual, all the function names are all lower-case, so I think it’s probably more correct to write them that way, anyway, even if they still work when written in camelcase on your particular system/server.

    a|x

  23. dauf Says:

    hello, i’m using JoomlaComponent: JoomGallery..

    How can i implement this function to it??

    Thanks!!

  24. Sinka Says:

    Nice post!
    Thanks

  25. Lynds Says:

    Nice Blog, where did you get the cool design? I will revisit

Leave a Reply