I had need recently to create thumbnails from a directory after I had uploaded images. I found a function that worked somewhere but found that it was unable to handle portrait images. I did a little bit of tweeking and this is the final result. It will open a directory where images are kept and look for the .jpg images. It will then create thumbnails of the images and save them in the designated directory. The thumbnails will be sized according to the set width or height you specify when calling the function.
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth, $thumbHeight ) { // 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} "; // load image and get image size $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" ); $width = imagesx( $img ); $height = imagesy( $img ); if ($width > $height){ // Create a landscape thumbnail // 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 imagecopyresampled( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height ); // save thumbnail into a file imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" ); imagedestroy($tmp_img); imagedestroy($img); }else { // Create new portrait sized thumbnail // calculate thumbnail size $new_width = $thumbHeight; $new_height = floor( $height * ( $thumbHeight / $width ) ); // create a new temporary image $tmp_img = imagecreatetruecolor($new_width, $new_height ); // copy and resize old image into new image imagecopyresampled( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height ); // save thumbnail into a file imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" ); imagedestroy($tmp_img); imagedestroy($img); } } } // close the directory closedir( $dir ); }
To call the function from within your php code:
Path to images is the path to where the images are kept and path to thumbnails is the where the thumbnails will be kept, tumbnail width is the width of the landscape images while thumbnail height is the height of the protrait images.
createThumbs( "images/", "images/thumbs/", 200, 150 );
If you have any comments or ways to make this better leave a comment below.
No comments:
Post a Comment