« Return

Generate thumbnails and manipulate images with GD library and PHPthumb

OPTION 1 - using PHP thumb library
<?php
function make_thumb() {
  
  $dir = './images/';
  $thumb_dir = './thumb/';
  $pattern = '_lg';
  $files = scandir($dir);
                                   
  foreach ($files as $key => $file) {     
    if (strpos($file, $pattern)):
    $gallery[] = $file;
    endif;
  }
  print_r($gallery);
  
  // ------------------------------------------------------------
  
  require_once 'php.phpthumb.lib/ThumbLib.inc.php';

  foreach ($gallery as $key => $value) {
  $thumb = PhpThumbFactory::create($dir . $value);
  $thumb->adaptiveResize(175, 175); # desired thumbnail width and height
  $thumb->save($thumb_dir . str_replace($pattern, '_sm', $value));
  }
	
}
?>

<?php make_thumb(); ?>
 
OPTION 2 - using Image Processing and GD
<?php
function make_thumb() {
  
  $desired_width = 150;             # desired thumbnail width
  $thumb_dir = './thumb/';          # directory where thumbnails will be saved
  $dir = './images/';               # directory where lg images are located
  $pattern = '_lg';                 # name pattern of lg images ( example: 001_lg.jpg )

  $files = scandir($dir);                                              
  foreach ($files as $key => $file) {   
    if (strpos($file, $pattern)):   # if != 0 then add to gallery array
    $gallery[] = $file;
    endif;
  }
  print_r($gallery);                # print array to review the selected files
  
  // ------------------------------------------------------------

  // generate the thumbnails on the gallery array
  foreach ($gallery as $key => $value) {
  $source_image = imagecreatefromjpeg($dir . $value);
  $width = imagesx($source_image);
  $height = imagesy($source_image);
  $desired_height = floor($height * ($desired_width / $width));
  $virtual_image = imagecreatetruecolor($desired_width, $desired_height);
  
  // copy source image at a resized size
  imagecopyresized($virtual_image, $source_image, 0,0,0,0, $desired_width, $desired_height, $width, $height);
  
  // string replace to update file names ( example: 001_lg.jpg to 001_sm.jpg )
  imagejpeg($virtual_image, $thumb_dir . str_replace($pattern, '_sm', $value), 100); # 0 to 100 ( control quality )
  }
  
}
?>

<?php make_thumb(); ?>