Create cropped thumbnails with GD Library

Published on May 9th, 2007 by admin

I've always preferred cropped thumbnails over resized images, they create a nice even space and flow better with the rest of the page.

What you will need

  • A server with php installed and GD Library enabled

The Process

  1. Prepare your php document.
  2. Get information for your image.
  3. Set the size and placement of the crop.
  4. Create the image.
  5. Add the border lines.
  6. Output the thumbnail.

Part One: Preparing your php document.

Open up your favorite script editor and make a new file. I prefer NotePad++ but any pure text editor will suffice.

Save the file as thumb.php

Part Two: Preparing your image

In this first step we need to grab our image and find its dimensions.

Grab the following code below and paste it into your php file.

//Your Image
$imgSrc = "image.jpg";

//getting the image dimensions
list($width, $height) = getimagesize($imgSrc);

//saving the image into memory (for manipulation with GD Library)
$myImage = imagecreatefromjpeg($imgSrc);

Part Three: Set the size and placement of the crop.

In the next step we have to decide how big we want our crop to be and where it wll go in relation to our image.

Copy and paste the following code below.

///--------------------------------------------------------
//setting the crop size
//--------------------------------------------------------
if($width > $height) $biggestSide = $width;
else $biggestSide = $height;

//The crop size will be half that of the largest side
$cropPercent = .5;
$cropWidth   = $biggestSide*$cropPercent;
$cropHeight  = $biggestSide*$cropPercent;

//getting the top left coordinate
$c1 = array("x"=>($width-$cropWidth)/2, "y"=>($height-$cropHeight)/2);

I like to place coordinates in my work, I think it makes it much easier to visualize what I’m try to achieve. In this case
I only need one coordinate (as opposed to four).

Cropping the image

Part Four: Creating the thumbnail image.

We have the crop size and position set, now all we need to do is create the thumbnail.

Copy the following code and paste it into your php document.

//--------------------------------------------------------
// Creating the thumbnail
//--------------------------------------------------------
$thumbSize = 60;
$thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($thumb, $myImage, 0, 0, $c1['x'], $c1['y'], $thumbSize, $thumbSize, $cropWidth, $cropHeight);

Part Five: Drawing the image border.

I like to add some style to my thumbnails and in this case a double border works quite nicely.

Copy and paste. . . you know the drill 😉

//--------------------------------------------------------
// Creating the lines
//--------------------------------------------------------
$lineWidth = 1;
$margin    = 0;
$green    = imagecolorallocate($thumb, 193, 252, 182);

for($i=0; $i<2; $i++){
//left line
imagefilledrectangle($thumb, $margin, $margin, $margin+$lineWidth, $thumbSize-$margin, $green);
//right line
imagefilledrectangle($thumb, $thumbSize-$margin-$lineWidth, $margin, $thumbSize-$margin, $thumbSize-$margin, $green);
//topLine
imagefilledrectangle($thumb, $margin, $margin, $thumbSize-$margin-$lineWidth, $margin+$lineWidth, $green);
//bottom line
imagefilledrectangle($thumb, $margin, $thumbSize-$margin-$lineWidth, $thumbSize-$margin-$lineWidth, $thumbSize-$margin,$green);
$margin+=4;
}

Part Six: Outputting the image

Copy and paste the following code and presto! Instant thumbnail!

//final output
header('Content-type: image/jpeg');
imagejpeg($thumb);
imagedestroy($thumb);

Your final result should look something like this.

Final Thumbnail

Conclusion

I hope this tutorial has been helpful, if you have any questions or suggestions pleaes feel free to post in my comments.

Leave a Reply




Comments

  • Post by Marick on June 16, 2007

    Thnx for this script, however I do have a question for you. Just curious if its possible to implement this script from a function call that executes the script at the point that its called. It seems that Im only able to run the script from the header of my PhP file as attempting to run it anywhere else results in a Header Output Already Started error.Thnx again :D

  • Post by Brant Tedeschi on September 4, 2007

    Excellent tutorial on cropping thumbnail images. I previously generated thumbnails with varying widths and it ruined the flow of the page.If you want to take a look at his script in action, look for submissions from this date on at http://www.celebritypwn.com.Thanks again!

  • Post by phpdiscovery.com on November 13, 2007

    Great Tutorial, I've never tried this before, then again it seems like an easy task. Great Explanation.

  • Post by johan hendrix on November 13, 2007

    great script! Do you also have a version that crops all the images in the folder? Like on http://icant.co.uk/articles/phpthumbnails/Greetz Johan

  • Post by Ivica on May 7, 2008

    hello. this is great, but I don't like croped images, because if someone puts hi picture of him self... and that picture is big, it often happends that croping cuts of his head so only stomak is showned :) I've seen that many times. However, I have one really stupid beginers question. Can you please tell me (send me on e-mail?), how to make a registration of new user with ability of putting avatar. I've found a tutorial how to make a registration, but I can't find one with avatar uploading included..... What is buging me specificly is when the user is registering and uploading his picture where shuld it be stored ? I want to make that user can create his own folder in witch will be his picture but I don't know how. THERE ARE STIL SOME STUPID PEOPLE LEFT :)

  • Post by Dan Grey on October 12, 2008

    Great script! I'm having trouble to integrate this on my site, I also can't 'double' the script to show 2 images on the same page, I think it's the header that's already sent by another page. Any solution to this? rgrds,

  • Post by manju on August 20, 2009

    The script is awesome. It crops the image and does not distort the image at all. I want to apply it to a number of images. I am trying to apply a for loop to this script but it takes only the first image from the complete set and resizes only the first one ignoring rest of the images. Please it would really help if you can tell me a method to apply this script to a number of images instead of one. So instead of $imgSrc = "image.jpg"; I need a set of images. Thnks

  • Post by manoj on December 5, 2009

    thanks for yor script, can you please tell me how to get input image dynamically instead of giving it directly as $imgSrc = "image.jpg"; plese make this statement dynamically, Thanks

  • Post by Joshua Bolduc on December 8, 2009

    Hi Manoj, please see this tutorial: http://www.bolducpress.com/tutorials/how-to-use-images-created-with-gdlibrary/ good luck!

  • Post by Locksmith Knoxville on September 28, 2010

    For reasons uknown i'm getting a blank page once i try and post a comment,do you recognize precisely why its taking?i'm implementing oprea web-browser

  • Post by SJ on February 12, 2011

    I took the above snippet and converted it into a function, if some are intrested http://www.vx10.co.uk/blog.php?Id=12

  • Post by vivek on February 19, 2011

    Hi sir, i read t tutorial wel,and i created t "thumb.php" file, i given t correct path of image and its name, and also i turned on t php_gd2.dll bt then too t webpage showing blank can u clarify my doubts sir waiting for your rply c u tak car

  • Post by Wander on April 13, 2013

    Thanks: still helpful in 2013 :-)

Popular Posts

Posts By Category

Supported by