Building a Photo Gallery

Document Sample
Building a Photo Gallery Powered By Docstoc
					Building a Photo Gallery

Page 1

I know you. You bought one of those fancy digital cameras and now you desperately
want to bore all your friends with the thousands of pics you've snapped. Or
Grandma/Auntie/Captain McAllister lives on the other side of the
state/country/globe/universe and is dying for a peek at your cute kids/furniture/pet

You could e-mail the photos and force everyone to wait for each image to download,
but are you sure Grandma can figure out how to view them? Or you could upload
them to a photo gallery site like Lycos Photocenter. But what if you have your own
site — say, — and you want the images to live there?

I have the perfect solution: Bust out all those PHP skills you've been cooking up and
sic them on a really simple photo gallery for your site. Just look at my photo gallery
filled with pics from a recent trip to San Francisco. Beautiful, isn't it? And I bet you
want one of your own now, right? Well let's take a look at what you'll need to get

What You'll Need

Before you roll up your eyelids, pour a cup of coffee, and dive in, let's make a list of
your photo-gallery-building necessities:

      Call me crazy, but a photo gallery just doesn't work the same without photos.
       So whip out your favorite digital camera, scanner, or maybe some original art
       you've done on the computer. I use a digital camera so I can just copy the
       images directly from the camera to the server, all formatted in chronological
       order. Now I could tell you what type of image to use — JPEG, GIF, or PNG —
       but maybe you should decide for yourself. Webmonkey's GIF vs. JPEG article
       may help you choose the right image format for you.
      Seeing that this software is written in PHP, you'll need a Web hosting service
       that can run your code.
      Since your photo gallery features both thumbnail and full-sized versions of
       your photos, you'll need to pick up some sort of image-editing software.
       ImageMagick is good, and free, and Photoshop is the full-blown industry
      You'll need to know a little JavaScript, too — not much, though, I promise.
       Just enough to let your users view the photos without having to reload the
       thumbnails page each time they return to it. If you're unsure about your
       JavaScripting abilities, peruse Thau's JavaScript Tutorial.
      Finally, you should also have a basic understanding of PHP. So if you're sitting
       there thinking, "What is this 'PHP' thing? Purple Hairy Pimples? What does
       that have to do with photo galleries?" you might want to get an Introduction
       to PHP first.

OK, now that you've got all those bases covered, let's jump right in to an explanation
of how this here image gallery works.
next page»

Page 2 — Thumbnails and Broomsticks

The first step is to create a thumbnail version of your images so people viewing them
don't have to download the full-sized version, which is the whole purpose of the
photo gallery.

Open up your favorite image editor (or, if you like to do things from the command
line, pop open a terminal window) and make yourself some thumbnails. As you
create them, make sure you give each one the same file name as the one you assign
to the full-sized image — just make sure to store them in different directories. You'll
understand why later, but for now, trust me.

A good rule of "thumb" for thumbnails is to size them so that the longest dimension
of the image is 60 to 120 pixels wide. In Photoshop you can do this by going to the
Image Menu -> Image Size, and just changing the value of the largest number to
100. If you have "constrain proportions" checked, it'll automatically fill in the value of
the other size for you. If you want more help, the Photoshop Crash Course is the way
to rock. If you're using ImageMagick, you can use mogrify to do your image
transformations by typing:

mogrify -geometry 100x75 -quality 60 *jpg

This command will convert all the JPEG images in your current directory to 100x75
pixel JPEGs, with a compression of 60 percent.

Now that you've got a bunch of thumbnails and full-size images, it's time to put them
on a server — unless, of course, you've been working on the server all along, in
which case you can go and get a nice tall cold beer/soda pop and congratulate
yourself on a job well done. You need to put all the images in a folder that the Web
server knows about. Make sure you put all the full-size images in one directory and
then make a directory inside of that directory called "thumbs," where you put, that's
right, the thumbnails.

Phew. Almost there! There's just one more step you need to do before writing the
image gallery itself. You need a way to let the gallery know the names of all the
images you have, and how many images there are total. There are a lot of ways to
do this, but the easiest is to just make a text file containing all the image names,
one per line. I call this file You can call it anything you want, just as long
as you don't call it late for dinner. On a Unix-type system you can do this by typing:

csh -c "ls *jpg >"

We run ls through csh just in case ls is set to display more information than just the
file name.

On windows, just drop to your command prompt and find the directory with all your
photos in it and type:
dir /b *.jpg >

Obviously this photo gallery will work with any image type that your browser
supports, so feel free to replace the *jpg with a *gif or *png if you need to.

Place this file in the same directory as the full-sized images (which, in fact, is where
we're going to place our two PHP files that run the gallery itself) and make sure you
remember what you named it.

Now that you've got your images, thumbnails, and list of photos all taken care of, it's
time to polish off that cup of coffee and pour yourself another. That's right ... IT'S
CODING TIME. And yes, I am doing my coding dance. Oh hush. You know you have
one too.

next page»

Page 3 — PHP is Cake

Actually, the PHP coding for your image gallery is easy. Honest. This whole PHP thing
is piece of cake: rich, sweet, chocolate cake with fresh cherries and whipped cream
and a nice tall glass of milk.

The index.php file is the workhorse of this photo gallery. Its job is to read in that list
of files you made earlier, throw the thumbnails for those files into a table, and make
the original, larger photo pop open in a new window when you click on it.

The first part of this page is just simple HTML with a JavaScript function that opens
up the pop-up window.

<title>photo gallery</title>
<script language="javascript">
  function photo_open(link, width, height)
       var photoWindow =,"photo",

<body bgcolor="#FFFFFF" text="#000000"
link="#00CCFF" alink="#00CCFF" vlink="#00CCFF">

         <table cellpadding="2" align="center"
     cellspacing="2" width="80%" border="0" align="center">
You'll need to pass the URL of the photo you're displaying to the JavaScript function,
as well as its height and width. And the name of your first born. Wait. Scratch that
last one.

You may notice, however, that when all is said and done and you're popping open
images left and right, there's no location bar, menu bar, or toolbar in the pop-up
window. If you want to put these elements back into the pop-up window (making it
less confusing for people to use), just find the element you want to appear in the
JavaScript function and change the "0" to a "1". For instance, to make the location
bar appear in the pop-up, change location=0 to location=1. It's really that easy.

You may have noticed the last line in this section of the file opens up a table, but
doesn't put any content into it. That's what the PHP portion of this file will do. Isn't
automation fun?

You'd better say yes because in the next section, we're going to cover automation!
Strap on those goggles, we're going on in.

next page»

Page 4 — Sizing up the Index

Now that you've got that lame boring old static HTML out of the way, it's time to
tackle the PHP code that makes this page fun and dynamic.

But first you need to tell PHP where you've put the files it needs. You also need to
learn about a handy PHP function, GetImageSize().

GetImageSize() takes one argument, a string containing the location of an image
(the version in PHP 4.0.5 will even let you give an URL to the image instead of a local
path), and returns a four-element array containing the following:

      Index 0: The width of the image, in pixels
      Index 1: The height of the image, in pixels
      Index 2: A flag containing the image type, 1 = GIF, 2 = JPG, 3 = PNG, 4 =
      Index 3: A string containing the height and width elements suitable for
       inserting in an <img> tag (e.g.: width="480" height="640").

If the string passed to GetImageSize() doesn't contain the location of an image, or
holds otherwise incorrect data, GetImageSize() will return null and print out an ugly
error message.

You're interested in three of these indexes (you don't need index number 2 since the
browser will detect the image type automatically for you). But you'll deal with
GetImageSize() in just a second. First, a little code to whet our appetite.

//initialize variables
$data_file = "";
$thumbnail_dir = "thumbs/";
$num_rows = 4;
$photos_per_row = 5;
$photos = file($data_file);
$total_photos = sizeof($photos);
$photos_per_page = $num_rows * $photos_per_row;
//check to see if the start variable exists in the URL.
//If not, then the user is on the first page - set start to 0
        $start = 0;
//init i to where it needs to start in the photos array
$i = $start;
$prev_start = $start - $photos_per_page;
$next_start = $start + $photos_per_page;

The first four lines of this section are important. These lines set up the photo gallery
dimensions and tell PHP where to find the thumbnails as well as the list of files. I
have the gallery set up so that my list of photos is in the same directory as the PHP
file and is named "" My thumbnails are in the same directory as the PHP
file named "thumbs." I also set it up to display four rows of five images per row, for
a total of twenty images on a page. If your thumbnails are larger, or if you have
elements on the page other than the photo gallery, you can adjust these variables.

The next line, $photos = file($data_file);, takes that text file and, using the
file() function, puts each line of the file into a separate element in an array. Then
in the next line, the sizeof() function sets how many photos there are, total, in the
gallery. The next three lines do some quick math to figure out how many photos
we're showing on each page and where we are in the photo gallery.

You also need to decide which photo to start with in your list of photos. You can do
that with the $start variable, which you'll use in the URL of the photo gallery (e.g.,
index.php?start=100 to start on photo number 100). If the variable isn't set, we
set it to zero because that means they're on the first page. (This will make more
sense when we get to the page navigation later.)

Once you've set up your variables, you can go about printing out the table that
contains all the thumbnails for your viewers to click on.

for ($row=0; $row < $num_rows; $row++){
  for ($col=0; $col < $photos_per_row; $col++){
      if($i < $total_photos){
        $thumbnail = $thumbnail_dir.trim($photos[$i]);
        $thumb_image_size = getimagesize($thumbnail);
        $image_size = getimagesize(trim($photos[$i]));
        print("<td align=\"center\"><
        a href=\"javascript:photo_open('photo_display.php?photo=
        ".$image_size[1]."');\"><img src=\"".$thumbnail.
        "\" ".$thumb_image_size[3]."></a></td>\n");
      } else {

//end table

There are quite a few things going on within this section of code. First, the outer for-
loop prints out each row of images, so it runs until the current row number is equal
to the total number of rows. Inside of this loop, it prints out a <tr> tag and then
starts another for-loop that prints out each table cell until the number of cells has
reached the number of photos we want in each row.

All the magic happens inside this inner for-loop. You use the variable $i as our
counter for the current photo you're showing. First you need to figure out where the
thumbnail for photo $i is by concatenating (the "." operator in PHP) the thumbnail
location to the image name that you're pulling out of the array of image names. Note
that you're using the trim() function on the image name in the array. This is
because the file() function inserts the entire line of the file, including the newline
character in each array element. The newline character is an invisible character at
the end of each line that tells your text editor where the line ends. In PHP, and many
other programming languages, it's represented in a text string as "\n". The trim()
function gets rid of any extraneous characters in a text string, like newlines.

Next, we use GetImageSize to determine the size of the thumbnail as well as the
size of the main image (so we can tell the JavaScript function how big to make the
window). Now you can print out the entire table cell, including the call to the
JavaScript pop-up, with the thumbnail image as the link. Note the JavaScript calls
the file "photo_display.php?" — we'll make this file later, so just leave it in there for
now. The if-else statement prints out a blank <td></td> cell in case you've run out
of photos in the gallery — this way you don't get broken tables or links. Finally, you
increment $i and start the loop all over again.

Now that you've got one page of thumbnails made, how do you view the rest of the
thumbnails in this gallery? Ah-ha! That's what the next section is all about:

next page»

Page 5 — Navigating the Gallery

OK so you've got a table of thumbnails, each one popping up the full-size image in a
new window. Great. But what if you've got more photos than will fit on one page?
You need a way to navigate through the list of photos. Luckily, way back in the
beginning of the script you set up two variables to show the starting position of the
page of thumbnails that exists before and the starting position of the page that
comes after. Don't worry your pretty little head if these starting positions don't
actually exist — we'll check for that as well. Here, take a look:

<div align="center">
//print out navigation links
if(($start == 0) && ($next_start < $total_photos)){

//you're at the beginning of the photo gallery

  <font face="arial, helvetica" size="2">
  <b><a href="view.php?start=<
  ?PHP print($next_start):?>">next page</a>
  <font color="#FF0000">&#187;</font></b>
elseif (($start > 0) && ($next_start < $total_photos)){

//you're in the middle of the photo gallery

  <font face="arial, helvetica" size="2">
  <b><font color="#FF0000">&#171;
  </font> <a href=\"view.php?start=
  <?PHP print($prev_start); ?>">prev page</a></b></font>
  <font face="arial, helvetica" size="2">
  <b><a href="view.php?start=<
  ?PHP print($next_start); ?>">next page</a> <font
elseif(($start == 0) && ($next_start > $total_photos)){

//you're in a photo gallery with only one page of photos


else {

//you're at the end of the photo galley

   <font face="arial, helvetica" size="2">
   <b><font color="#FF0000">&#171;</font>
   <a href="view.php?start=<?PHP print($prev_start); ?>
   ">prev page</a></b></font>
Looks a little daunting? Well, don't worry — it's going to all make sense soon
enough. The current page of the photo gallery can exist in four different states:

   1. This is the first page of the gallery. This means you have a next page, but not
      a previous page.
   2. This is a page in the middle of the gallery. This means you have a previous
      page and a next page.
   3. This is the last page of the gallery. This means you only have a previous
   4. This is a photo gallery with only one page. There are no next or previous

Our if-else statement checks for each of these conditions. You use the variables set
earlier in the page, $previous_start and $next_start, to determine what the
starting photo of the previous or next page will be, and then based on the current
starting photo ($start) and the number of photos total in the gallery
($num_photos), you can do some simple logic checking.

The first clause, if(($start == 0) && ($next_start < $total_photos)), when
evaluated as true, says that you're on the first page ($start == 0) and there are
more photos in the gallery after this page ($next_start < $total_photos), so it
only prints out a next page link.

The second clause shows that you're not at $start == 0, but there are more photos
after this page. So that means there are photos before this page (start isn't zero)
and there are more photos after this page, so a next and previous link need to be

The third clause asks if you're on the first page again, but if there aren't anymore
photos in the gallery, it knows you've got a photo gallery where all the photos fit on
this one page, so it doesn't print out anything.

The final else says that since you've checked all three other states, you must be on
the last page of the gallery, so it prints out only a previous page link. You might have
also noticed the <?PHP print($PHP_SELF); ?> statements. These are used so that,
no matter what you name your PHP file, it'll always link to itself. ($PHP_SELF is a PHP
variable that prints out the filename of whatever file it's in.)

Finally, don't forget to close up your HTML document with the correct HTML tags.


Woah! You can now navigate through pages of thumbnails. But notice what happens
if you click on one of the thumbnails: Our JavaScript function gives us an error.
Why? Because we haven't made the page that actually displays the full-sized photo
yet. But have no fear! Just go onto the next section. Go on. It's OK. I'll be right there
waiting for you.

next page»
Page 6 — Finishing Up

Wow! You're almost done with your photo gallery! There's only one thing left to do:
Make the page that actually displays the full-size photo. You could, if you wanted to,
display the photo directly in the pop-up window by linking JavaScript to the specific
photo location. But the way we're going to do it gives us a little more leeway, and it
isn't too much of a sacrifice because the file is pretty small and simple.

In the photo gallery thumbnail page, you'll see that each cell has a link that goes to:


This makes the JavaScript function pop open a window the size of the image, with
the URL photo_display.php?photo=. All photo_display.php has to do is read in
the name of the photo from the photo= part of the URL and display it. We use the
GetImageSize() function again to get the size of the image so you can use the
height and width tags like good Webmonkeys. Also notice the extra elements in the
<body> tag — these just turn off the borders of the Web page so the picture bleeds
to the edge of the window.

<title><?PHP print($photo);?></title>

        $photo_size = getimagesize("$photo");
<body bgcolor="#FFFFFF" marginheight="0"
marginwidth="0" leftmargin="0" topmargin="0"

<img src="<?PHP print($photo);
?>" <?PHP print($photo_size[3]);
?> name="photo">


Pretty simple, huh? Well congratulations! You've got yourself an automated photo
gallery, and it works pretty well with very little set up time. But now what do you do?
Well, folks, I hate to say it, but this photo gallery isn't perfect. There are many
improvements yet to be made, such as:

       Add a "close this window" link in the photo pop-up.
       Add a system to let users post comments about each photo. (Bonus: Use a
        database to store the comments!)
       Make the system run entirely off a database so you don't have to play with
        text files.
       Have it generate the thumbnails on the fly using the image functions for PHP.
       Make it object oriented so it's even more extendable!
With a little more work, you could create a world-class image gallery browser that
lets you edit your photos, add more photos, send your photos to friends, or even
create your own hotornot site. I hope you enjoy yourself as you experiment. Good