Picture Perfect

8/13/2010 9:30 AM By

This next one is really useful if you’ve got a whole pile of images sitting in a folder (or folders) and you want to easily generate a gallery for them. Let’s take an example of pictures you’ve taken on a trip and organized into date-based folders. The structure looks like this:

  • 2010
    • 04
      • 01
      • 02
      • 03

So we’ve got the main folder, which is a year, then the month, then the days, with the images stored in each day folder. Now we write a page to house these images, like this:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Pictures From My Trips</title>
</head>
<body>
    <section id="april-pics">
        <ul id="photos-list">
            <!-- PHP goes here -->
        </ul>
    </section>
</body>
</html>

And finally, insert this PHP:

<?php
// the directory, where your images are stored
$imgdir = '/images/2010/04/01';

// list of filetypes you want to show
$allowed_types = array('png','jpg','jpeg','gif');

$dimg = opendir($imgdir);
while($imgfile = readdir($dimg))
{
    if(in_array(strtolower(substr($imgfile,-3)),$allowed_types))
    {
        $a_img[] = $imgfile;
        sort($a_img);
        reset ($a_img);
    }
}
// total image number
$totimg = count($a_img);

for($x=0; $x < $totimg; $x++)
{
    $size = getimagesize($imgdir.'/'.$a_img[$x]);

    // Make changes to the images' size to show thumbnails.
    $halfwidth = ceil($size[0]/2);
    $halfheight = ceil($size[1]/2);
    echo "\t\t\t".'<li><a rel="lightbox" href="'.$imgdir.'/'.$a_img[$x].'"<img src="'.$imgdir.'/'.$a_img[$x].'" width="'.$halfwidth.'" height="'.$halfheight.'" /></a></li>'."\r"; // Tabs & carriage return added to improve final rendered readability.
}
?>

So what’s going on with that? Well, we’ve set a variable, $imgdir, then we parse that directory for each image that corresponds to an array of filetypes (based on extension). Next, we count the total number of images and use a for() statement to do something to each image until we run out of images; ($x=0, then we tell it to go while $x < $totimg, incrementing $x by one each time.)

Finally, it echoes a few tabs to line up the echoed code with the rest of the HTML, inserts a <li>, then creates a link to the image itself for a lightbox effect, and finally inserts the image itself using an <img> tag. From there, we can use some CSS to style and lay out the list into a gallery of sorts; perhaps the usual grid, or maybe we could use some JavaScript to create some sort of carousel, slider, or other fancy effect.

Whatever you decide to do, this is a great, simple way to generate a gallery automatically based on a folder of images.

Tags:

Comments are closed.