DevTek.Org 
Your PHP Solutions Resource 









 

Basic Image Gallery Using PHP

Most everyone has a digital camera these days. The greatest strength of a digital camera is the fact that you can take so many pictures with it and not have to worry too much about a picture coming out badly with regards to developing cost. However, it's also one of the biggest weaknesses because you then have to create an HTML page to display all the pictures, and that can be tedious.

This tutorial will allow you to just dump the images into a folder on your webserver and by modifying a single variable, have all your images display without writing any code or HTML. We'll then take the tutorial a bit futher to show how you can create a simple text file to display descriptions of the images.

We're going to use six images for demonstration. In reality, there are 12 images (two of each). The original unresized image, and a smaller (320x240) one for quick display. You can actually make the small images thumbnails if you want. That's up to you.

The following folder structure is used for puposes of this tutorial. you can set up any folder structure you want provided you change the variables in the script.

Main folder
 - This script
 - image_gallery folder
   - Thumbnails (small images)
   - big folder
     - Full resolution versions of the small images
              

This tutorial assumes you know how to resize images to make thumbnails.

So first, let's show you what it does.




And here's the code that did this.

<?php

$images 
"image_gallery/"# Location of small versions
$big    "big/"# Location of big versions (assumed to be a subdir of above)
$cols   2# Number of columns to display

if ($handle opendir($images)) {
   while (
false !== ($file readdir($handle))) {
       if (
$file != "." && $file != ".." && $file != rtrim($big,"/")) {
           
$files[] = $file;
       }
   }
   
closedir($handle);
}

$colCtr 0;

echo 
'<table width="100%" cellspacing="3"><tr>';

foreach(
$files as $file)
{
  if(
$colCtr %$cols == 0)
    echo 
'</tr><tr><td colspan="2"><hr /></td></tr><tr>';
  echo 
'<td align="center"><a href="' $images $big $file '"><img src="' $images $file '" /></a></td>';
  
$colCtr++;
}

echo 
'</table>' "\r\n";

?>


So let's go through the code bit by bit to explain how it works.

We have three variables $images, $big, and $cols. $images is responsible for the location of the smaller images which it will use to build the "thumbnails" or contact sheet. $big is responsible for holding the location of the larger, full resolution images. Technically, you could put all the files in the same directory and use an identifier on the full resolution images to provide uniqueness between it and the "thumbnail". For instance, appending the string "big" or such to the end of the filename would be sufficient, and then modify the a href line to append the string to the end of the filename. I'll mention this when we get to that part. Finally $cols is responsible for determining how many columns we want to display the images in. For this tutorial, I've set this to two. It's important to keep the "/" at the end of the folder names. You'll break the script if you don't.

The next thing we're doing is opening the folder containing the images as defined by the $images variable. We're looping through the directory and adding every file it finds to an array called $files[]. Take note of the nested if statement. It's job is to prevent adding the ., .., and $big folders to the array, because those would show up as broken images. It's important to note that this will add any file found in the $images folder to the array and attempt to display it as an image. There are ways around this with more code, but this is a really basic image gallery script. The last thing we do in this part is close the resource allocated to the directory open.

Now, we initialize the $colCtr to zero and output the first part of the table. Our next step is to loop through the $files[] array and fill that into a table. We want a couple things to happen here. The first is that we want to display the "thumbnails" and secondly we want someone to be able to click the thumbnail and have it display the full resolution image.

The first thing we do in our for loop is to test whether the $colCtr is the same value as $col that we defined. If it is, we're going to close the table row, put an hr, and then start a new row.

Here's where the real meat is. We're outputting an a href which uses three variables to build the link to the full resolution image. $images . $big . $file which in this tutorial works out to: image_gallery/big/something.jpg. Next, we output the image as $images . $file.

I mentioned earlier that you could keep all the files in the same folder and distinguish the full resolution image with a unique identifier like appending "big" to the filename. So, for example, let's say we have an image of a dog, in which the "thumbnail" is called dog.jpg and the full resolution image is called dogbig.jpg. You can use the PHP str_replace() function to replace the "." with "big." or vice versa if you used the string "small" on the thumbnail, in which you could also use the PHP str_replace() function to replace the string "small" with "" (nothing). Either way works. It's up to you.

Next we increment the $colCtr variable so we can output the number of columns we want. And then lastly, close the table when we've output all the images.

Well, that's how you do it. Pretty simple huh?

Now.... Let's suppose you want to include text below each image to describe it for your viewers. This is pretty simple too. Let's first look at how it shows up, then we'll examine the code.



Our Halloween Pumpkin

My little ghoulish helpers


Balloon Fiesta!

Ash meets Cinderella on her 7th B-day


Jayden's first snowday

Converting our garage to a halloween cave

And here's the code that did this.

<?php

$images 
"image_gallery/"# Location of small versions
$big    "big/"# Location of big versions (assumed to be a subdir of above)
$cols   2# Number of columns to display
$text   "image_gallery_description.txt";

$fh=fopen($text"r");

while(!
feof($fh))
{
  
$temp explode(","$line);
  
$description[$temp[0]] = $temp[1];
  
$line=fgets($fh);
  unset(
$temp);
}

if (
$handle opendir($images)) {
   while (
false !== ($file readdir($handle))) {
       if (
$file != "." && $file != ".." && $file != rtrim($big,"/")) {
           
$files[] = $file;
       }
   }
   
closedir($handle);
}

$colCtr 0;

echo 
'<table width="100%" cellspacing="3"><tr>';

foreach(
$files as $file)
{
  if(
$colCtr %$cols == 0)
    echo 
'</tr><tr><td colspan="' $cols '"><hr /></td></tr><tr>';
  
$allfiles .= $file ',<br />';
  echo 
'<td align="center"><a href="' $images $big $file '"><img src="' $images $file '" /></a><br />' $description[$file][0] . '</td>';
  
$colCtr++;
}

echo 
'</table>' "\r\n";
echo 
$allfiles;
?> 


Since this bit of code is very similar to the previous example, we're just going to cover the pieces that are different.

We've got a new variable called $text which is the name of the text file containing our descriptions. Let me break off here and show you what the contents of the text file are.

PICT0168.JPG,Balloon Fiesta!
PICT0259.JPG,Our Halloween Pumpkin
PICT0271.JPG,Converting our garage to a halloween cave
PICT0282.JPG,My little ghoulish helpers
PICT0524.JPG,Ash meets Cinderella on her 7th B-day
PICT0633.JPG,Jayden's first snowday
              

One very important piece to remember is that you need to have an empty line as the last line in the text file. If you don't then the description for the last image won't show up. This is because our loop condition is !feof and since we're pulling in a whole line at a time from the text file, not having the blank line at the end means your last entry has the end-of-file marker at the end and therefore satisfies the condition and will not pull that line into the array. Another thing to keep note of is that there isn't a space on either side of the comma. This is important. Put a space between it and the filename and you break the script. Put it between the comma and the description and you'll have a space in front of the description under the picture.

That last paragraph covered quite a bit of what is happening, but let's go over it step by step. Our while condition is testing to see if the end-of-file is TRUE. If so, it stops. Otherwise it does the below.

Since our text file is delimited with a comma seperating the image name and the description, we're going to explode the line off that comma to seperate it into an array.

The problem we have to solve now is that the filename and the description at this point are two seperate elements in the array. To fix this we're going to reassign the filename as the KEY and VALUE which is the description text. If you plan on using commas in your description, then you need to use a different delimiter (maybe a semi-colon).

Once this reassignment is done, here's what our array looks like:

Array
(
    [] => 
    [PICT0168.JPG] => Balloon Fiesta!

    [PICT0259.JPG] => Our Halloween Pumpkin

    [PICT0271.JPG] => Converting our garage to a halloween cave

    [PICT0282.JPG] => My little ghoulish helpers

    [PICT0524.JPG] => Ash meets Cinderella on her 7th B-day

    [PICT0633.JPG] => Jayden's first snowday

)
              

Next we get the next line, and unset the $temp array so it's empty for the next iteration.

The last thing we do is add a bit of code to the line which outputs our td in the table to output a linebreak, and ouput the description text.

Now if you were paying attention you'll notice I didn't mention two lines in the above code. The reason being is that these normally wouldn't be there in your final version. The line $allfiles .= $file . ',<br />'; creates a variable containing all the filenames ending in a comma, seperated by a newline, which we output at the end with an echo. This is just a helper for you to get a list of filenames to put in your description text file so all you have to do is type the description after it.

Well, that's how you do it. Pretty simple huh?



Copyright 2004-05,
All rights reserved.
Powered by PHP   Powered by PSPad   Powered by MySQL   Last Modified
May 15, 2012 @ 12:51