Generating JPG/GIF/PNG thumbnails in PHP using imagegif, imagejpeg, imagepng
Don't you just adore the simplicity of PHP? It is a cake walk to create thumbnails in PHP, without any plugins like imagemagick or NetPBM, and it is super fast too. Here's the simple code.
Don't you just adore the simplicity of PHP! It is a cake walk to create thumbnails in PHP, without any plugins like imagemagick or NetPBM, and it is super fast too. Here's the simple code.
The following code takes a "source image" from a "source path" and makes a thumbnail out of it, placing the thumbnailed image into a "thumb path." It is fairly straightforward so I won't waste time explaining stuff. Post a comment below if you have any questions or problems.
- Elements that you'll probably have to edit are highlighted in red
– Comments are in green
Make sure the path for thumbnails is writeable, the imagejpeg function takes care of writing by itself, you don't need to fwrite etc.
$sourcePath = 'images/'; // Path of original image
$sourceUrl = 'http://domain.com/images/';
$sourceName = 'test.jpg'; // Name of original image
$thumbPath = $sourcePath . 'thumbs/'; // Writeable thumb path
$thumbUrl = $sourceUrl . 'thumbs/';
$thumbName = "test_thumb.jpg"; // Tip: Name dynamically
$thumbWidth = 60; // Intended dimension of thumb
// Beyond this point is simply code.
$sourceImage = imagecreatefromjpeg("$sourcePath/$sourceName");
$sourceWidth = imagesx($sourceImage);
$sourceHeight = imagesy($sourceImage);
$targetImage = imagecreate($thumbWidth,$thumbWidth);
imagecopyresized($targetImage,$sourceImage,0,0,0,0,$thumbWidth,
$thumbWidth,imagesx($sourceImage),imagesy($sourceImage));
imagejpeg($targetImage, "$thumbPath/$thumbName");
// By now, the thumbnail is copied into the $thumbpath
// as the file name specified in $thumbName, so display
echo "<img src='$thumbUrl$thumbName' alt=''>";
?>
This above example is for JPEG format. Replace all occurences of "jpeg" in the above code with "gif" and you're good to go for GIF files! Similarly, you can edit the "jpeg" to "png" and you're good to go. For instance, replace "imagejpeg" with "imagegif" or "imagepng".
Eventually, you can also cobble together some code to figure out the file type of a $sourceImage dynamically (from a directory on the server for instance) and apply the appropriate functions. This is just an example to give you an idea!
Just FYI, my setup on the server is as follows:
- Root HTTP folder:
/home/domain/public_html/ - Images folder:
/home/domain/public_html/images/
This becomes our$sourcePathbecause this is where the original image comes from. - Thumbs folder:
/home/domain/public_html/images/thumbs/(this folder is CHMODed 744, and is our$thumbPath)
Pingback: PHP Thumbnail Generator | Danny Kopping | RIA-CODER.COM