How to create thumbnails

I need to create thumbnails using PHP. I have a folder with a lot of jpg files that are constatntly increasing.

What can I do?
wcokaAsked:
Who is Participating?
 
TeRReFConnect With a Mentor Commented:
0
 
Rob_JeffreyIT/ProgrammingCommented:
Here is a great function:

function makeThumbnail($o_file, $t_ht = 100) {
   $image_info = getImageSize($o_file) ; // see EXIF for faster way
   switch ($image_info['mime']) {
       case 'image/gif':
           if (imagetypes() & IMG_GIF)  { // not the same as IMAGETYPE
               $o_im = imageCreateFromGIF($o_file) ;
           } else {
               $ermsg = 'GIF images are not supported<br />';
           }
           break;
       case 'image/jpeg':
           if (imagetypes() & IMG_JPG)  {
               $o_im = imageCreateFromJPEG($o_file) ;
           } else {
               $ermsg = 'JPEG images are not supported<br />';
           }
           break;
       case 'image/png':
           if (imagetypes() & IMG_PNG)  {
               $o_im = imageCreateFromPNG($o_file) ;
           } else {
               $ermsg = 'PNG images are not supported<br />';
           }
           break;
       case 'image/wbmp':
           if (imagetypes() & IMG_WBMP)  {
               $o_im = imageCreateFromWBMP($o_file) ;
           } else {
               $ermsg = 'WBMP images are not supported<br />';
           }
           break;
       default:
           $ermsg = $image_info['mime'].' images are not supported<br />';
           break;
   }
   
   if (!isset($ermsg)) {
       $o_wd = imagesx($o_im) ;
       $o_ht = imagesy($o_im) ;
       // thumbnail width = target * original width / original height
       $t_wd = round($o_wd * $t_ht / $o_ht) ;

       $t_im = imageCreateTrueColor($t_wd,$t_ht);
       
       imageCopyResampled($t_im, $o_im, 0, 0, 0, 0, $t_wd, $t_ht, $o_wd, $o_ht);
       
       imageJPEG($t_im);
       
       imageDestroy($o_im);
       imageDestroy($t_im);
   }
   return isset($ermsg)?$ermsg:NULL;
}

makeThumbnail( $filename, 50);

This returns the thumbnail.  So you need to save the result into a file and reference that file in an IMG SRC.
I have the function in it's own file and use that file as the IMG SRC - passing a global variable of the filename to convert.
The file being referenced returns a proper JPG header and echo's the return right to the browser.
0
 
arun80_ininCommented:
try this

function create_thumb_nail($image_name,$sourcepath,$destpath,$new_image_name,$maxheight,$maxwidth)
{
      $picture =$sourcepath.$image_name; # picture fileNAME here. not address
      
      $solitted_name=explode('.',$picture);
      $image_type=$solitted_name[count($solitted_name)-1];

      if(strcasecmp($image_type,"jpg")==0)
            $src_img=@ImagecreateFromJpeg($picture);
      else if(strcasecmp($image_type,"jpeg")==0)
            $src_img=@ImagecreateFromJpeg($picture);
      else if(strcasecmp($image_type,"gif"==0))
            $src_img=ImagecreateFromGif($picture);
      else if(strcasecmp($image_type,"png")==0)
            $src_img=@ImagecreateFromPng($picture);
      

      if ($src_img=="")
            return false;
      else
      {      
            $oh = imagesy($src_img);  # original height
            $ow = imagesx($src_img);  # original width
            
            $new_w = $maxwidth;
            $ratio = ($ow / $new_w);
            $new_h = round($oh / $ratio);
            if ($new_h > $maxheight)
            {
                  $new_h = $maxheight;
                  $ratio = ($oh / $new_h);
                  $new_w = round($ow / $ratio);
            }


            // note TrueColor does 256 and not.. 8
            $dst_img = ImageCreateTrueColor($new_w,$new_h);
            ImageCopyResized($dst_img, $src_img, 0,0,0,0, $new_w, $new_h, ImageSX($src_img), ImageSY($src_img));
                        
            if (is_file($destpath.$new_image_name))
            {
                  unlink($destpath.$new_image_name);
            }
                  
            if(strcasecmp($image_type,"jpg")==0)
                  $fin_img=ImageJpeg($dst_img, $destpath.$new_image_name);
            else if(strcasecmp($image_type,"jpeg")==0)
                  $fin_img=ImageJpeg($dst_img, $destpath.$new_image_name);
            else if(strcasecmp($image_type,"gif"==0))
                  $fin_img=imagegif($dst_img, $destpath.$new_image_name);
            else if(strcasecmp($image_type,"png")==0)
                  $fin_img=imagepng($dst_img,$destpath.$new_image_name);
            if ($fin_img=="")
                  return false;
            else      
                  return true;
      }
}
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
lukeinjaxCommented:
Here's a function that you can point towards an image directory and it will generate thumbnails for each of the images in the directory based upon the dimensions given at the top of the function. I use it my photo galleries so I can simply ad a photo to a folder and the next time someone visits the page, it will automatically thumbnail the new image. It looks at each image in the directory and if it doesn't have a thumbnail, it creates it. If it does, it moves on. Just set up a directory to put all your pictures in and create a "thumbnails" sub-directory. Then call the function, passing in the images directory and off you go...

<?
      function generate_thumbnails($images_dir) {
            $imagemagick_path = "/sw/bin";
            $max_thumbnail_width = 150;
            $max_thumbnail_height = 150;
            $sleep_time = 1000;
            $count = 0;
            
            $thumbs_dir = $images_dir . "thumbnails";
            
            if ($thumbs_handle = opendir("$thumbs_dir/")) {
                  while (false !== ($thumb_file = readdir($thumbs_handle))) {
                        $thumbstring.=$thumb_file;
                  }
            
                  closedir($thumbs_handle);
            }
                  
            if ($handle = opendir("$images_dir")) {
                  while (false !== ($file = readdir($handle))) {
                        if (stristr($file,'jpg') && !stristr($file,'tb_')) {
                              if (!stristr($thumbstring,$file)) {
                                    //*****************image resize code starts here*****************                                   
                                    usleep($sleep_time);
                                    $size = getimagesize("$images_dir$file");
                                                                        
                                    // Wide Image
                                    if($size[0] > $size[1]) {  
                                          $thumbnail_width = $max_thumbnail_width;
                                          $thumbnail_height = (int)($thumbnail_width * $size[1] / $size[0]);                                                        
                                    }  
                                    
                                    // Tall Image
                                    else {
                                          $thumbnail_height = $max_thumbnail_height;
                                          $thumbnail_width = (int)($thumbnail_height * $size[0] / $size[1]);
                                    }
                                    
                                    exec("$imagemagick_path/convert -geometry " .
                                     "{$thumbnail_width}x{$thumbnail_height} " .
                                     "$images_dir/$file $thumbs_dir/tb_$file");
                        
                                    //*****************image resize code ends here*****************
                              }      

                              $pictures[] = $file;
                              $count++;
                        }
                  }
            
                  closedir($handle);
            }

            sort($pictures);
            reset($pictures);
      }
?>
0
 
cristi_2112Commented:
or this... :)

/*
* $sourcefile = path/name to source image
* $targetfile = path/name to target image
* $extf = extension of image (you can take it with explode($sourcefile, '.'); and then the last member of the array
* $max_width $max_height = properties of the new image (in case they already are smaller, the thumbnail is just a copy of the original image
* $image_quality = between 1 and 100
*/
function createThumb($sourcefile, $targetfile, $extf, $max_width, $max_height, $image_quality = 100)
{
     eval('$src_img = ImageCreateFrom'.$extf.'($sourcefile);');
     $orig_x = ImageSX($src_img);
     $orig_y = ImageSY($src_img);

     $new_y = $max_height;
     $new_x = $orig_x/($orig_y/$max_height);

     if ($max_width >= $orig_x )
     {
          $new_y = $orig_y;
          $new_x = $orig_x;
     }
     elseif ($new_x > $max_width)
     {
          $new_x = $max_width;
          $new_y = $orig_y/($orig_x/$max_width);
     }

     $dst_img = ImageCreateTrueColor($new_x,$new_y);

     ImageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $new_x, $new_y, $orig_x, $orig_y);

     eval('Image'.$extf.'($dst_img, $targetfile, $image_quality);');
     ImageDestroy($src_img);
     ImageDestroy($dst_img);
}
0
 
floorman67Commented:
or this :)

<?php
// TStarGallery 1.0 engine
// With basic PHP knowledge you can understand what's happening here.
// Don't blame me for writing non-perfect code for I do not care.
// If there is an error or something, mail me at tstar@taillandier.de


// Read the current directory, throw out non-jpg/gif/png + thumbfiles
// --------------------------------------------------------------------
$dirfiles = array();

$handle=opendir('.');
while ($file = readdir($handle)) {
   if
   ((
   strtolower(strrchr($file, '.')) == ".jpg" OR
   strtolower(strrchr($file, '.')) == ".jpeg" OR
   strtolower(strrchr($file, '.')) == ".png" OR
   strtolower(strrchr($file, '.')) == ".gif"
   )
   &&
   (
   strstr($file, ".thumb.jpg") == ''
   ))
   {
         array_push($dirfiles, $file);
   }
}
sort ($dirfiles);
closedir($handle);

// Write the beginning of the basic table for displaying the thumbs.
// Modify this section to make it fit your own website.
// -----------------------------------------------------------------
echo "<table width=\"505\" border=\"0\" cellpadding=\"2\" cellspacing=\"0\" id=\"structure\"><tr>";


// Read the valid filenames from the array, have your way with every single one of them
// ------------------------------------------------------------------------------------

foreach($dirfiles as $aktuellesfile)
{
// Elements of the filename are cut into pieces
$dateiendung = strrchr( $aktuellesfile, '.' );
$dateiname = substr_replace ($aktuellesfile, '', -strlen($dateiendung) );


// First a routine for creating a thumb
createthumb ($dateiname, $dateiendung);
// Now open up a table cell
echo "<td>";
// Second a routine for showing a thumb
showthumb ($dateiname, $dateiendung);
// Close the table cell
echo "</td>";
// And make a linebreak after every 5 thumbs
if(++$cnt % 5 == 0) echo "</tr>";
}

// Finished
exit;

   
// Function to create a thumbnail if it doesn't already exist
// -----------------------------------------------------------------
function createthumb ($thumbdateiname, $thumbdateiendung)
{
      $fullname = $thumbdateiname.$thumbdateiendung;
      $fullthumbname = $thumbdateiname.$thumbdateiendung.".thumb.jpg";
      
      // If thumb exists,nothing will happen
      if (file_exists($fullthumbname) OR strstr($fullname, ".thumb.jpg") != '')
      {  
      }
      // If thumb doesn't exist,it's created now
  else
  {      
            if ((strtolower($thumbdateiendung) == ".jpg") OR (strtolower($thumbdateiendung) == ".jpeg")){
            $src_img = imagecreatefromjpeg($fullname);
            }
            if (strtolower($thumbdateiendung) == ".gif"){
            $src_img = imagecreatefromgif($fullname);
            }
            if (strtolower($thumbdateiendung) == ".png"){
            $src_img = imagecreatefrompng($fullname);
            }
      
            $origx=imagesx($src_img);
        $origy=imagesy($src_img);
            
            // Maximum width and height of the thumbnails
        $max_x = 102;
        $max_y = 116;
        
        // Calc, if thumb has has to be squeezed from width or height
            if($origx >= $origy AND $origx > $max_x)
            {
            $faktor = $origx / $max_x;      
            $new_x = $origx / $faktor;
        $new_y = $origy / $faktor;      
            }
            
            elseif($origy > $origx AND $origy > $max_y)
            {
            $faktor = $origy / $max_y;      
            $new_x = $origx / $faktor;
        $new_y = $origy / $faktor;      
            }
            
            else
            {
            $new_x = $origx;
            $new_y = $origy;
        }
        
        // Squeeze and write it into a file
            $dst_img = imagecreatetruecolor($new_x,$new_y);
        imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_x,$new_y,imagesx($src_img),imagesy($src_img));
        imagejpeg($dst_img, $fullthumbname, 50);
      }
}                    

// Function to show a thumbnail
// -----------------------------------------------------------------
function showthumb ($thumbdateiname, $thumbdateiendung)
{
      $fullname = $thumbdateiname.$thumbdateiendung;
      $fullthumbname = $thumbdateiname.$thumbdateiendung.".thumb.jpg";
      if (file_exists($fullthumbname))
      {
      echo "<a href=\"$fullname\"><img src =\"$fullthumbname\" border=\"0\"></a>";
      }
      else
      {
      }

}
?>
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.