PHP

Create thumbnails in PHP

Let’s see how we can read all images from a directory and create a thumbnail for each one:

function createThumbnails( $imagespath, $thumbnailspath, $size )
{
$directory = opendir( $imagespath );
while (false !== ($filename = readdir( $directory ))) {
if($filename=='.' || $filename=='..') continue;
if(is_dir($imagespath.$filename)) continue; 
$info = pathinfo($imagespath.$filename);
if ( strtolower($info['extension']) == 'jpg' )
{
  echo "<font color='green'>Creating thumbnail for image $filename <br /></font>";
  $img = @imagecreatefromjpeg( $imagespath.$filename );
  if(!$img) 
  {
	echo "<font color='red'>Unable to create thumbnail for image $filename <br /></font>";
	continue;
  }
  $width = imagesx( $img );
  $height = imagesy( $img );
  $new_width = $size;
  $new_height = floor( $height * ( $size / $width ) );
  $imgtmp = imagecreatetruecolor( $new_width, $new_height );
  imagecopyresized( $imgtmp, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
  imagejpeg( $imgtmp, $thumbnailspath.$filename );
}
}
closedir( $directory );
}

Example

createThumbnails("images/", "images/thumbs/", 60);