Create a copy of an image as a thumbnail. You get a great function that use the GD library to create the new thumbnail file.

Often you need to change the size/dimensions of images in your web site.

One example could be if you let your visitors upload an image of themself when they register. For different reasons it could be important to make sure the images have a specific size, so they don’t mess upp hte design of your layout. Another example could be if you have a photo gallery for your self, then it’s nice to have the same size for images.

Together with standard PHP installations you get something that is called GD. This package is made for creating and modifying images directly from PHP. From PHP 4.3 you get GD bundled and only have to make sure it’s activated/compile, but this is the case most of the times.

Read about PHP’s GD functions: here.

GD is great, but it can be a little bit hard to understand at the beginning. So therefor I will give you a Great function for creating thumbnails to start with:

What you do is to call the function with four parameters:

  • imageDirectory – Where is your original images stored?
  • imageName – What’s the filename of the file to make a thumbnail of?
  • thumbDirectory – Where to store the newly created thumbnail?
  • thumbWidth – What width do you want for the thumbnail?
function createThumbnail($imageDirectory, $imageName, $thumbDirectory, $thumbWidth)
{
$srcImg        = imagecreatefromjpeg("$imageDirectory/$imageName");
$origWidth    = imagesx($srcImg);
$origHeight   = imagesy($srcImg);

$ratio               = $origWidth / $thumbWidth;
$thumbHeight   = $origHeight * $ratio;

$thumbImg      = imagecreate($thumbWidth, $thumbHeight);
imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, imagesx($thumbImg), imagesy($thumbImg));

imagejpeg($thumbImg, "$thumbDirectory/$imageName");
}

createThumbnail("img", "theFileName.jpg", "img/thumbs", 100);

The function is not that hard to read. Simply copy the whole script and try it. The way I call the function you have to store your images in a directory called “img” in the same directory where this script will be. You need a directory called “thumbs” inside the img-directory. You also need to make sure the webserver have write permissions to this directory, otherwise it can’t save the output file.

I choose to set the width to 100px wide. What happens with the height is a little bit special. The height is changed just as much as the width is. Let’s say the original image is 200px wide and 300px high. Then the width will be 100px ofcourse and the height is also changed to the half as the width and becomes 150px.

Hope you get some use of this script and have fun with it and use it as much as you like!!

Similar Posts:

  • Share/Bookmark