Monday, 22 July 2013

Create thumb from directory useing php

function getExtension($str) {
         $i = strrpos($str,".");
     
       
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth, $thumbheight )
{
  // open the directory
  $dir = opendir( $pathToImages );


  while (false !== ($fname = readdir( $dir ))) {
   
         $image_path=$pathToImages.$fname;
  
  echo $upload_image=$pathToImages.$fname;
       
       
        $thumbnail=$pathToThumbs."thumb_".$fname;
         $info = pathinfo($pathToImages . $fname);
        echo "<pre>";
         print_r($info);
       
    // continue only if this is a JPEG image
    if ( strtolower($info['extension'] ) != ' ' )
    {
      list($width, $height) = getimagesize($upload_image);
        $newwidth = $thumbWidth;
        $newheight = $thumbheight;
       
        /*echo "<pre>";
        print_r($upload_image);
        print_r($width.$height);
        die;*/
       
        $thumb = imagecreatetruecolor($newwidth, $newheight);
       
       
        $ext = getExtension($fname);
        $ext = strtolower($ext);
                       
        if($ext=="jpg" || $ext=="jpeg" )
        {
            $source = imagecreatefromjpeg($upload_image);
        }
        else if($ext=="png")
        {
            $source = imagecreatefrompng($upload_image);
        }
        else
        {
            $source = imagecreatefromgif($upload_image);
        }

        imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        imagejpeg($thumb, $thumbnail);
       
    }
  }
  // close the directory
  closedir( $dir );
}

createThumbs("live/","thumb/",170,170);

"live/" is directory in with your real images.

"thumb/" is that you want to create image.