How to Create Thumbnails from Image using PHP
First Step: Install GD
Image processing in PHP can be done powerfully with a library, GD. GD image library needs to be installed and activated on your PHP to be able to do image processing.
To check if GD is installed, check your phpinfo:
Open a file phptest.php (that contains following code) in your browser:
<?php
phpinfo()
?>If you find GD in the output of the browser, this means GD is installed on your server.
If GD is not installed, install it.
Second Step: Start Coding in PHP for Thumbnail generation
The code below creates a function named createThumbNail that will get three parameters: path to the directory that contains images, second to the directory where thumbnails would be places and 3rd parameter is the width of the thumbnail images.
<?php
function createThumbNail($pathToImages, $pathToThumbs, $thumbWidth )
{
// open the directory
$dir = opendir( $pathToImages );
// loop through it, looking for any/all JPG files:
while (false !== ($fname = readdir( $dir ))) {
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'jpg' )
{
echo "Creating thumbnail for {$fname} <br />";
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
}
}
// close the directory
closedir( $dir );
}
?>
Now, you can call the function in the same php file to genearte thumbnails:
<?php
// files is the folder containing images, files/thumbnails/ is the folder in which thumbnails would be created and 50 is the width of the thumbnail.
createThumbNail("files/","files/thumbnails/",50);
?>Note, we have used following PHP Gd functions for image thumbnail generation in createThumbNail():
* imageCreateFromJPEG() to create a copy to work on of a .jpg image.
* imageCreateFromPNG() to create a copy to work on of a .png image.
* imageSX() to get the width of the original image.
* imageSY() to get the height of the original image.
* ImageCreateTrueColor() to create a new truecolour image object.
* imageCopyResampled() to resample the image.
nice post for beginner
Post your Answer