Creating a simple photo gallery

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Creating a simple photo gallery

    In this tutorial I will show you how to create a simple photo gallery. The script creates thumbnail images if needed and displays all images in the given directory.

    Step 1.
    First of all we need to make a short analysis what we need to create a usable but simple gallery script. The idea is that we create a simple Php file which checks all files in the given directory. In case of an image file the script check if it is a thumbnail or a normal image. If the actual image is a normal photo than we check whether it has a thumbnail image in this directory or not. If not then we create it. After all files were checked the script displays all thumbnail images in a table as a link to the original size image. That is the small description. Now let's see how to realize this.

    Step 2.
    The first function we need to implement is a thumbnail generator. This code will be responsible for analyzing the actual directory and creating the thumbnail images if necessary. So the first steps are:
    Open the directory
    Read all entries one by one
    Check if the current entry is a file or not

    The code looks like this:
    Code:
    <?php
        // Open the actual directory
        if ($handle = opendir(".")) {
            // Read all file from the actual directory
            while ($file = readdir($handle))  {
                // Check whether tha actual item is a valid file
                if (is_file($file)){
    ?>
    Now we know that the actual entry is a file. So we need to check whether it is a thumbnail image or not. As we are using strong naming conventions all thumbnail filenames must have the format name_th.jpg where the _th.jpg is important for us. So we can use this information and search for this substring in the filename. If we find it we can say that this file is a thumbnail image and we set a flag to store this information.
    Code:
    <?php
                    // Check whether the actual image is a thumbnail
                      if (strpos($file,'_th.jpg')){
                          $isThumb = true;
                      } else {
                          $isThumb = false;
                      }
    ?>
    If the file was a thumbnail file then we have nothing more to do. If not then we have some more tasks. First we need to process the filename and get all information about it as base filename, file extension and directory name. If the file extension shows that the actual file is not a jpeg file where the extension should be jpg or jpeg then we skip this file. However if it is an image file we will check whether a thumbnail file exists for it yet or not. If the thumbnail file doesn't exists then we create a new one for it using imagejpeg() and resizeImage() functions. The resizeImage is not a PHP built in function but we create it in this script. For more explanation see our older tutorial regarding resizing images.
    Code:
    <?php
                      if (!$isThumb) {
                          // Process the file string
                          $dirName  = substr($file,0,strpos($file,basename($file)));
                          if (strlen($dirName) < 1) $dirName = '.';
                          $fileName = basename($file);
                          $fileMain = substr($fileName,0,strrpos($fileName,'.'));
                          $extName  = substr($fileName,strrpos($fileName,'.'),
                                              strlen($fileName)-strrpos($fileName,'.'));
                          
                          // Check if the actual file is a jpeg image
                          if (($extName == '.jpg') || ($extName == '.jpeg')){
                            $thmbFile = $dirName.'/'.$fileMain.'_th.jpg';
                            // If a thumbnail dosn't exists tahn create a new one
                            if (!file_exists($thmbFile)){
                                imagejpeg(resizeImage($file,$thmb_width,$thmb_height),$thmbFile,80);
                            }
                        }
                      } 
    ?>
    Here I have to warn you that PHP limits the script execution time and maximum memory usage. Image resize is a quite time and memory consuming process so if you have a lot of image in a directory it can happen that the script will be terminated before it could finish. Besides this the default memory allowed for a script is 8 MB which is reasonable in almost all cases but if you want to resize a big image file it can require 64Mb or more.

    Step 3.
    Let's create the main function to display the gallery. The displayPhotos() function first calls the above implemented generateThumbnails() function to prepare thumbnails. After this step we go through again on the directory entries and display all of the thumbnail images. All images will be a link to the original image. So if the visitor clicks on it the original photo will be displayed. To make it a little bit nicer we organize the images in a table format.

    The function looks like this:
    Code:
    <?php
    function displayPhotos(){
        global $columns;
        
        generateThumbnails();
        $act = 0;
        // Open the actual directory
        if ($handle = opendir(".")) {
            // Read all file from the actual directory
            while ($file = readdir($handle))  {
                // Check whether tha actual item is a valid file
                if (is_file($file)){
                    // Check whether the actual image is a thumbnail
                      if (strpos($file,'_th.jpg')){
                        ++$act;
                        if ($act > $columns) {
                            echo '</tr><tr>
                               <td class="photo"><a href="'.getNormalImage($file).'">
                                   <img src="'.$file.'" alt="'.$file.'"/></a></td>';    
                            $act = 1;
                        } else {
                            echo '<td class="photo"><a href="'.getNormalImage($file).'">
                               <img src="'.$file.'" alt="'.$file.'"/></a></td>';    
                        }
                          
                      }
                  }
            }
        }    
    }
    ?>
    Step 4.
    The last task is to make a simple HTML block where we call the displayPhotos() function. Here you can add a title and create the corresponding table code. You can extend the code with css formatting to make it nicer.

    complete code
    Code:
    <?php
    
    $columns     = 5;
    $thmb_width  = 120;
    $thmb_height = 80;
    
    function resizeImage($originalImage,$toWidth,$toHeight){
        
        // Get the original geometry and calculate scales
        list($width, $height) = getimagesize($originalImage);
        $xscale=$width/$toWidth;
        $yscale=$height/$toHeight;
        
        // Recalculate new size with default ratio
        if ($yscale>$xscale){
            $new_width = round($width * (1/$yscale));
            $new_height = round($height * (1/$yscale));
        }
        else {
            $new_width = round($width * (1/$xscale));
            $new_height = round($height * (1/$xscale));
        }
        // Resize the original image
        $imageResized = imagecreatetruecolor($new_width, $new_height);
        $imageTmp     = imagecreatefromjpeg ($originalImage);
        imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, 
                           $new_width, $new_height, $width, $height);
    
        return $imageResized;
    } 
    
    function generateThumbnails(){
        global $thmb_width,$thmb_height;
        
        // Open the actual directory
        if ($handle = opendir(".")) {
            // Read all file from the actual directory
            while ($file = readdir($handle))  {
                // Check whether tha actual item is a valid file
                if (is_file($file)){
                    // Check whether the actual image is a thumbnail
                      if (strpos($file,'_th.jpg')){
                          $isThumb = true;
                      } else {
                          $isThumb = false;
                      }
                  
                      if (!$isThumb) {
                          // Process the file string
                          $dirName  = substr($file,0,strpos($file,basename($file)));
                          if (strlen($dirName) < 1) $dirName = '.';
                          $fileName = basename($file);
                          $fileMain = substr($fileName,0,strrpos($fileName,'.'));
                          $extName  = substr($fileName,strrpos($fileName,'.'),
                                              strlen($fileName)-strrpos($fileName,'.'));
                          
                          // Check if the actual file is a jpeg image
                          if (($extName == '.jpg') || ($extName == '.jpeg')){
                            $thmbFile = $dirName.'/'.$fileMain.'_th.jpg';
                            // If a thumbnail dosn't exists tahn create a new one
                            if (!file_exists($thmbFile)){
                                imagejpeg(resizeImage($file,$thmb_width,$thmb_height)
                                         ,$thmbFile,80);
                            }
                        }
                      } 
                   }
               }
        }
        
    }
    
    function getNormalImage($file){
        $base = substr($file,0,strrpos($file,'_th.jpg'));
        if (file_exists($base.'.jpg')) return $base.'.jpg';
        elseif (file_exists($base.'.jpeg')) return $base.'.jpeg';
        else return "";
    }
    
    function displayPhotos(){
        global $columns;
        
        generateThumbnails();
        $act = 0;
        // Open the actual directory
        if ($handle = opendir(".")) {
            // Read all file from the actual directory
            while ($file = readdir($handle))  {
                // Check whether tha actual item is a valid file
                if (is_file($file)){
                    // Check whether the actual image is a thumbnail
                      if (strpos($file,'_th.jpg')){
                        ++$act;
                        if ($act > $columns) {
                            echo '</tr><tr>
                               <td class="photo"><a href="'.getNormalImage($file).'">
                                   <img src="'.$file.'" alt="'.$file.'"/></a></td>';    
                            $act = 1;
                        } else {
                            echo '<td class="photo"><a href="'.getNormalImage($file).'">
                               <img src="'.$file.'" alt="'.$file.'"/></a></td>';    
                        }
                          
                      }
                  }
            }
        }    
    }
    
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "DTD/xhtml1-transitional.dtd">
    <html>
    <head>
       <title>Photo Gallery</title>
    </head>
    <body>
      <center><h3>Photo Gallery</h3></center>
      <table align="center"><tr>     
        <?php displayPhotos(); ?>
      </table>        
    </body>   
    
    
    [/html]

    #2
    hey...good tutorial....thanks....i have one question.....can yo make a file or a tutorail... about gallery but with password, each user that is able to put a password on his album?or give me an idea how I could do that, an example .. something...that could help me!!!thanks

    Comment


      #3
      ok, tell me if I'm wrong, one can then have two files, eg image.jpg and image_th.jpg, and the latter will be the thumbnail of image.jpg?
      Why cry for a soul set free?

      Comment


        #4
        How we resize the original image with this script?

        How to resize the original image with this script?

        original image : 600 x 480
        thum image : 120 x 80

        thanks

        Comment

        Working...
        X