Solved

How to create thumbnails

Posted on 2006-07-19
8
376 Views
Last Modified: 2008-03-10
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?
0
Comment
Question by:wcoka
8 Comments
 
LVL 29

Accepted Solution

by:
TeRReF earned 100 total points
ID: 17142004
0
 
LVL 9

Expert Comment

by:Rob_Jeffrey
ID: 17142126
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
 
LVL 2

Expert Comment

by:arun80_inin
ID: 17144544
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
ScreenConnect 6.0 Free Trial

Discover new time-saving features in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

 

Expert Comment

by:lukeinjax
ID: 17151727
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
 
LVL 9

Expert Comment

by:cristi_2112
ID: 17152999
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
 
LVL 5

Expert Comment

by:floorman67
ID: 17169525
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

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question