Automatically Generate a Photo Gallery from a Directory of Images

Creating a Photo Gallery isn’t such a hard task. My favorite way to present photos is simply a grid of thumbnails that people may pick and choose from as they see ones that interest them. Clicking on a thumbnail brings up a larger version. Could be a direct link to the larger photo or something fancier like a modal box. If you are creating a fairly small gallery, hand coding this grid of thumbnails is probably fine, but if you are creating a fairly large gallery or you anticipate doing a lot of adding/editing/swapping of photos, you may want to consider a better solution. And that solution is…. An automatically generating photo gallery!

When I say “Auto Generating”, I don’t mean that that it takes the pictures for you. This gallery won’t even create the thumbnails for you. What it DOES, is build itself dynamically from your directory of images. So when you want to add new photos, you simply drop the new photo and thumbnail in the directory and you are done! Removing photos just means removing the photos from the image directory. We use PHP for this web wizardry.

VIEW DEMODOWNLOAD FILES

1. The Basic HTML Page Structure

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>Auto Generating Photo Gallery</title>
	<link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
	<div id="page-wrap">
		<img src="resources/header.png" alt="Photo Gallery" /><br />
		<!-- Thumbnails go here -->
	</div>

</body>
</html>

2. Preparing the Images

We are going to write the PHP to look for a very specific naming convention for our images. Any image with the text “-thumb” in its title will be considered a thumbnail image and will be displayed on the page. The direct link to the larger size image will be that exact file name with the “-thumb” part stripped away from it. For this gallery to work properly, you’ll need to put BOTH the thumbnail image and the larger size image in the images directory following this naming convention.

So, you’ll need to create two images for each image you wish to present in the gallery. Using just typical right-off-the-camera file names, your file names will be something like this:

Large version: IMG_0813.jpg
Thumbnail: IMG_0813-thumb.jpg

For a nice grid-like look, keep all your thumbnails a consistent size. I used 100px x 100px in this example.

3. The CSS

Very simple styling here. We are going to do a hard CSS reset, then create a page-wrap to keep our gallery centered, and then create a couple of classes for our thumbnails.

*					{ margin: 0; padding: 0; }
body				{ background: url(resources/bg.png) top center repeat-x #2a2a2a; }
a img, img 			{ border: none; }

#page-wrap			{ width: 800px; margin: 0 auto; }

.photo-link			{ padding: 5px; margin: 5px; border: 1px solid #999; display: block; width: 100px;
					  float: left; }
.photo-link:hover	{ border-color: white; }

4. The PHP

The PHP is what is going to do all the heavy lifting here. We are going to tell it where to look, and how many thumbnails we want per-row. Then it is going to look in that directory for any images that have a “-thumb” as part of their name and all them to an array.

Then (if it finds any), it will go through a loop echoing out each thumbnail onto the page wrapped in an anchor link (with the special class we styled in the CSS) which links to the full size version of the photo. At the end of each row, it will clear the float for us. If it doesn’t find any images, we get a short message saying so.

<?php

	/* settings */
	$image_dir = 'images/';
	$per_column = 6;

	/* step one:  read directory, make array of files */
	if ($handle = opendir($image_dir)) {
		while (false !== ($file = readdir($handle)))
		{
			if ($file != '.' && $file != '..')
			{
				if(strstr($file,'-thumb'))
				{
					$files[] = $file;
				}
			}
		}
		closedir($handle);
	}

	/* step two: loop through, format gallery */
	if(count($files))
	{
		foreach($files as $file)
		{
			$count++;
			echo '<a class="photo-link" rel="one-big-group" href="',$image_dir,str_replace('-thumb','',$file),'"><img src="',$image_dir,$file,'" width="100" height="100" /></a>';
			if($count % $per_column == 0) { echo '<div class="clear"></div>'; }
		}
	}
	else
	{
		echo '<p>There are no images in this gallery.</p>';
	}

?>

5. The JavaScript

Our Gallery is totally functional at this point, but let’s fancy it up a little bit by making the full size images pop up in a Modal box. We’ll just jQuery for this and the FancyBox plugin.

Download the files, then include the links to the JavaScript files in your header. Then “activate” the FancyBox effect on the images when the DOM is ready:

<script type="text/javascript" src="js/jquery-1.2.3.pack.js"></script>
<script type="text/javascript" src="js/jquery.fancybox-1.0.0.js"></script>

<script type="text/javascript">

	$(function(){

		$(".photo-link").fancybox({ 'zoomSpeedIn': 500, 'zoomSpeedOut': 500, 'overlayShow': true }); 

	});

</script>

We’re done!

This can be a huge time saver. You could even probably train someone with no web coding experience whatsoever how to add photos to a directory with specific names, empowering them to update their own gallery! While this is example absolutely works, do you have any ideas for how it could be better? For one thing, caching might be a good idea. So that the PHP doesn’t have to scour a web directory for every single visitor. Let us know in the comments what else you think could be improved.

VIEW DEMODOWNLOAD FILES

Comments

The carousel plugin ( http://sorgalla.com/projects/jcarousel/ ) would be a great addition to the gallery in order to fit the images into a smaller space. That is one thing that could see being added with little effort, yet is very beneficial to developers and designers.

Marc Grabanski | August 13th, 2008 @ 1:24 pm

[...] Automatically Generate a Photo Gallery from a Directory of ImagesA photo gallery that builds itself dynamically from a directory of images. So when you want to add new photos, you simply drop the new photo and thumbnail in the directory and you are done! Removing photos just means removing the photos from the image directory. [...]

Just one wish : captions!

Peter | August 13th, 2008 @ 3:04 pm

One more wish : thumbnail generation by the GD library …

Peter | August 13th, 2008 @ 3:10 pm

Hey… what is wrong with my email?

I am writting something simmilar, only it uses jQuery’s thickbox plugin.

SeanJA | August 13th, 2008 @ 3:24 pm

And it uses the GD library to create the thumbnails*

SeanJA | August 13th, 2008 @ 3:24 pm

Cool!

I’ve been looking for a similar setup as this. Also, I’m very interested in SeanJA’s project, as I’m interested in learning more JQuery.

Forrest | August 13th, 2008 @ 4:23 pm

Cool, could be an ideal way of presenting client work & revisions.

liam | August 13th, 2008 @ 5:08 pm

Thanks for sharing your knowledge; with your help we are getting a more friendly internet for rookies like me.
Thanks again!

elcodigodebarras | August 14th, 2008 @ 7:37 am

I’ve made a simple image gallery a while ago. It reads the images from a folder and supports categories and automatic thumbnail generation. I even put (really) simple template support in it.

See: http://61924.wepwnyou.net/category/coding/imgbrowz0r/ for more info. :)

Frank | August 14th, 2008 @ 9:31 am

[...] a quick note that I wrote up a tutorial (with demo and download) on how to Automatically Generate a Photo Gallery from a Directory of Images as an exclusive for Script & [...]

I have been looking for something like this but that can pull the images from my Picasa Albums. Having a gallery that can display my Picasa (or Flikr for the rest of you) would be AMAZING!!!!

Adam | August 15th, 2008 @ 6:01 am

The gallery on opera browser not work, dont see big images.

Ruben Rojas | August 15th, 2008 @ 6:02 am

The problem i have with things like this is that you say it’s easy, but then say “you just have to make the thumbs and resize the photos”. For some people even that’s asking too much!

i’m working on something similar, but instead i’m having it read the original pics, then generate thumbs and “mid-size” photos on the fly. you could do the same with some more php code… i might “borrow” some of your ideas… haha.

jason | August 15th, 2008 @ 7:01 am

Hey I just may give it a try.
“You could even probably train someone with no web coding experience whatsoever how to add photos….” Yep that’s me, well kinda.

keith | August 15th, 2008 @ 11:38 am

An amazing coincidence, as I released a very similar script on my site just 4 days ago, and then an update on the 14th.

Similar in approach, but mine is a directory lister, listing all files and folders in the directory by default. What sets it apart however, is that it calls absolutely no external files. All included images/javascript/css is pulled from within the php script itself. Check it out to see what I mean.

http://greg-j.com/2008/08/14/released-phpdl-v2-and-phpdl-lite/

I’ll be doing a series of these actually, so if you’d like a guest writer let me know.

As for the caching, I have several solutions that I have used over the years. Being the author of MSRS, MSLS and now MSAS (anyone who owns a resource site would know what they are), I can tell you that while caching can be useful, reading directories is much less intensive than you may think.

Greg Johnson | August 16th, 2008 @ 5:58 pm

Wow, this looks really easy!

Yonghwee | August 17th, 2008 @ 5:42 am

I would suggest a fairly simple addition (see - http://mrphp.com.au/code/project/miscellaneous/image-cache-using-phpthumb-and-htaccess) to handle thumbnail creation and improve the automation of the whole system, therefore elevating the problem “jason” mentioned above.

Andy | August 17th, 2008 @ 6:25 am

I would like to create this PHP page in Cold Fusion. I can build the Cold Fusion index page if you tell me the steps in logical fashion. Then I can share for you to include because as fantastic as PHP may be, it is not the be-all-end-all and some developers actually prefer CF.

Mustang | August 17th, 2008 @ 7:19 pm

[...] Script & Style » Automatically Generate a Photo Gallery from a Directory of Images (tags: webdev webdesign tutorials tutorial slideshow gallery from a directory) [...]

This is a great project for anyone wanting to learn/tinker with php and javascript. I really like ZenPhoto (zenphoto.org) as far as album apps go. It auto-generates from images in a folder, creates cached thumbnails/full-sized image and does tagging/comments/captions/sorting/searching etc.

Jason Beaird | August 19th, 2008 @ 11:24 am

Great project! But I think that is better if images can be subdiveded in more pages. For example 12 images for each page…is it possible?

I hope you understand me..i’m italian..

Federico | August 19th, 2008 @ 12:58 pm

[...] a quick note that I wrote up a tutorial (with demo and download) on how to Automatically Generate a Photo Gallery from a Directory of Images as an exclusive for Script & [...]

Has anyone actually tested this on Opera?
Because it doesn’t work!

Besides, if anyone wants a quick and easy gallery, just use ZenPhoto.
You don’t need to upload images 1 by 1.
Just drop the whole folder of images into the /albums folder, and voila!

Maikel | August 19th, 2008 @ 9:56 pm

in safari i gett a horizontal scrollbar. does anybody know how to fix that bug? cheers! greetings, ben

benjamin | August 30th, 2008 @ 1:31 am

[...] - Automatically Generate a Photo Gallery from a Directory of Images [...]

Websites You Shouldn´’t Have Missed in August | August 31st, 2008 @ 1:09 pm

[...] - Automatically Generate a Photo Gallery from a Directory of Images [...]

[...] Automatically Generate a Photo Gallery from a Directory of Images Tutorial and free download on creating your own gallery. PHP does some of the heavy lifting by looking through a directory for you and building the gallery from that. [...]

» So You Need A Photo Gallery Website? | September 2nd, 2008 @ 6:34 am

[...] - Automatically Generate a Photo Gallery from a Directory of Images [...]

if anyone want the thumbnails automatically create, use the folowing script:

first define these 3 functions:

function createThumb_square($source,$dest) {
$thumb_size = 100;
$size = getimagesize($source);
$width = $size[0];
$height = $size[1];

if($width> $height) {
$x = ceil(($width - $height) / 2 );
$width = $height;
} elseif($height> $width) {
$y = ceil(($height - $width) / 2);
$height = $width;
}

$new_im = ImageCreatetruecolor($thumb_size,$thumb_size);
$im = imagecreatefromjpeg($source);
imagecopyresampled($new_im,$im,0,0,$x,$y,$thumb_size,$thumb_size,$width,$height);
imagejpeg($new_im,$dest,100);
}

function createThumbName($file,$pic_format,$thumb_mask)
{

$pic_name_length = strlen($file);

$pic_name_length = $pic_name_length - strlen($pic_format);

$pic_name = substr($file, 0, $pic_name_length);

$pic_name_thumb = $pic_name.$thumb_mask.$pic_format;
return $pic_name_thumb;
}

function fileExists($dir, $file)
{
if ($handle = opendir($dir)) {

while (false !== ($file_name = readdir($handle))) {
if($file_name == $file){
return true;
}
}
return false;
}
}

Then extend the php-script in index.php:

/* step one: read directory, make array of files */
if ($handle = opendir($image_dir)) {
while (false !== ($file = readdir($handle)))
{
if ($file != ‘.’ && $file != ‘..’)
{
$file_thumb = createThumbName($file,$pic_format,$thumb_mask);
if(strstr($file,’-thumb’))
{
$files[] = $file;
}elseif (!fileExists($image_dir,$file_thumb))
{
echo ‘reingelaufen’;
// echo ‘neuer Thumbname ist:’.” “.$file_thumb;
createThumb_square($image_dir.$file,$image_dir.$file_thumb);
}

}
}
closedir($handle);
}

Thats it. Now you can drop all your images without thumbnails in your folder and start the index.php. You have to start it twice, because the first running creates thumbnails.

AndyToolshed | September 2nd, 2008 @ 11:23 pm

Nice! Thanks for sharing that Andy!

Chris Coyier | September 3rd, 2008 @ 6:22 am

[...] Automatically Generate a Photo Gallery from a Directory of Images Tutorial and free download on creating your own gallery. PHP does some of the heavy lifting by looking through a directory for you and building the gallery from that. [...]

[...] can create your own Photo Gallery only by uploading your photos in a image directory on line. At scriptandstyle.com you can find all the files available for download and a small guide if you want to understand how [...]

Very good article, especially with Andys addition. A few things need correcting however.
1) There is a problem with Andys code above however. The pic_format and thumb_mask variables in the call
createThumbName($file,$pic_format,$thumb_mask);
are not initialize. Initialize the variables or change the call to createThumbName($file,’.jpg’,'-thumb’);

2) I noticed that the clear-class was missing in style.css when I changed the $per_column to 5, add this: .clear { clear: both; }

3) I wanted the pictures in chronological order so I added
sort($files);
first in step two in index.php

Mats Hammarstedt | September 6th, 2008 @ 4:20 am

Any tips on integrating this with wordpress?

weefs | September 9th, 2008 @ 12:22 am

[...] - Automatically Generate a Photo Gallery from a Directory of Images [...]

[...] - Automatically Generate a Photo Gallery from a Directory of Images [...]

[...] Automatically Generate a Photo Gallery from a Directory of images (JavaScript, PHP) | Demo [...]

[...] Automatically Generate a Photo Gallery from a Directory of Images [...]

[...] This is a robust script put out by the folks over at script and style, and the best feature is that you don’t have to manually resize photos. Just drag and drop into a folder, and presto. You’re good to go. Works well with larger galleries. Uses the fancybox technique to overlay the image. Visit site [...]

Javascript image gallery roundup | Mike Meisner | October 8th, 2008 @ 7:09 am

Hi,

I have a problem with your script, can we put the script many times in one page? (hummmm my english is so crap..)
Because with this script: http://www.ndoherty.com/demos/coda-slider/1.1.1/
There is juste one page, and I want to put a gallery in each “pannel”.
Look the “bug”=> http://photol.free.fr/coda
The gallery keep the latest photos but without the thumbs…
Ths for help me :)

pol | October 9th, 2008 @ 5:09 am

@ steve

I just figured out captions can be displayed by via IPTC data embedded in the photo. This is the PHP I used.

$filename = “$image_dir$file”;
$size = GetImageSize ($filename,$info);
$iptc = iptcparse ($info["APP13"]);
$headline = $iptc["2#105"][0];

I inserted this after count++. Then added a title attribute to the img tag of title=’$headline’.

$iptc["2#105"][0]; outputs the Headline field located in the IPTC CONTENT dialog in ‘File Info’ of the jpg in Photoshop. Fill the caption you want and off you go.

Took me a while as I know virtually nothing about PHP but I got there. Hope that’s useful to somebody.

Toby | October 10th, 2008 @ 1:22 pm

I should note that I’m using the script with the jQuery Galleria plugin instead of FancyZoom so I’ve done away with the thumbnails aspect of the script altogether as Galleria does this for you.

Toby | October 10th, 2008 @ 1:41 pm

[...] Automatically Generate a Photo Gallery from a Directory of Images Tutorial and free download on creating your own gallery. PHP does some of the heavy lifting by looking through a directory for you and building the gallery from that. [...]

If you Google ‘Imagemagick PHP’, you’ll find *lots* of scripts using this incredible graphics manipulation library to do things like automatic thumbnail creation, watermarking images, adding captions, etc.

DeadlyDad | October 15th, 2008 @ 2:52 pm

[...] While you’re there, why not check out their tutorial on generating a photo gallery from a directory of images? [...]

[...] Script & Style » Automatically Generate a Photo Gallery from a Directory of Images - [...]

how could i use lightbox instead with this??

chris | November 2nd, 2008 @ 12:54 pm

also how could i make it only load about 10 images per page, so it adds links to the bottom to the next pages?

chris | November 2nd, 2008 @ 12:56 pm

Hi all,

This is the great script i think, impressive layout, so i used this gallery in one of my project. But in that project there is a requirement of adding caption under the picture.

i tried to modified js file, bt i dint got that from where caption or title can be shown under the picture zoomout.

i am not getting how to pass this caption from php code.

i also passed title tag in img and also href but same……..

echo ‘‘;

i also tried the method shown by Toby but couldnt got succeed,

can any one please help me? i need it urgently. please someone help me.

Thanks in advance.
arm

arm | November 11th, 2008 @ 6:39 am

[...] un recurso para poder generar galerías de la manera mas sencilla posible. Se trata de este script que te permite generar galerías preparadas con solo colocar las imágenes en una carpeta de tu [...]

[...] Visit » [...]

This is a great gallery! I am tasked with updating a flat HTML file gallery, and the requirements include verbose captions with hyperlinks to parent projects. (My images are scientific visualizations, not casual photos.) Do you have any suggestions for a floating text box next to the “floating” image that could contain text with hyperlinks?

Diana Diehl | November 26th, 2008 @ 4:42 pm

I have an error in IE:

Notice: Undefined variable: count in /home/content/d/c/p/dcpro/html/kathyspub/wip/system/core/core.functions.php(637) : eval()’d code on line 91

I’m using this inside of an ExpressionEngine template, any ideas on how to fix.

thanks,

hobz | December 5th, 2008 @ 9:53 am

[...] Automatically Generate a Photo Gallery from a Directory of Images [...]

THANKYOU,
i am eternaly grateful for your work, see i got a bit tipsy one night and said i can make websites, ive already got one but it is a used design, and the person im making one for needs a photo gallery and you just saved my life

joe | December 10th, 2008 @ 12:56 pm

[...] Automatically Generate a Photo Gallery from a Directory of Images [...]

[...] Automatically Generate a Photo Gallery from a Directory of Images [...]

[...] Scriptandstyle nam nudi dinamičnu galeriju koju je vrlo jednostavno nadopunjavati. Potrebno je samo, u za to određenu mapu, dodati sliku i thumbnail. PHP i JS učine sve ostalo. [...]

Galerije slika i gdje ih pronaći | Kroativ | December 17th, 2008 @ 2:52 pm

I love the script. My only gripe is (as with almost every other lightbox type of galleries) is the wait for the image to open. I understand it may take a couple seconds to load a large image (server/connection etc..), but if the only reason to wait for an image to load is just to look at the loading animation, then it really is a turn off for me.

Randy | December 20th, 2008 @ 8:32 am

[...] lo que quieres es programar tu propio script, para personalizarlo a tu gusto, tienes este sencillo tutorial, pero necesitaras saber PHP para poder [...]

Scripts para galerias de imagenes | Enigma Tres | December 30th, 2008 @ 2:51 am

hi guys…i used the Andy’s script for thumbnail images….but i dont understand why the secondo time i load the page…it shows 2 times the same image but in the folder there is just one

anyone help?

Markitto | January 3rd, 2009 @ 8:12 am

[...] 24. Auto Generating Gallery [...]

[...] Script & Style » Automatically Generate a Photo Gallery from a Directory of Images - Creating a Photo Gallery isn’t such a hard task. My favorite way to present photos is simply a grid of thumbnails that people may pick and choose from as they see ones that interest them. Clicking on a thumbnail brings up a larger version. Could be a direct link to the larger photo or something fancier like a modal box. If you are creating a fairly small gallery, hand coding this grid of thumbnails is probably fine, but if you are creating a fairly large gallery or you anticipate doing a lot of adding/editing/swapping of photos, you may want to consider a better solution. [...]

Handy little tool this, thanks for sharing :)

Rik Weber | February 3rd, 2009 @ 2:29 pm

Is there anyway to call random -thumb images with the appropriate link to the full image?

For example, I want my main page to display 6 random thumbnail that links to the full image.

I was looking around for a display random image with php script, but none of them display random images with a specific filename or a text contained in the filename.

Roger | February 16th, 2009 @ 10:47 am

get a fix on entrance appealing commandeer boldness
[url=http://forum.buffalostate.edu/index.php?showuser=11168]cialis online[/url] a malaise ago yen to be established sample mollypamper exemplar.

Hoftoxrat | February 20th, 2009 @ 1:01 pm

thank you very much, i was really waiting for a script like this, its really nice, thank you very much,

Mohammed Rizmy | February 28th, 2009 @ 5:41 am

I think this tutorial is too much time consuming, instead there are tons of packages available to create the web photo gallery of your Images. You even dont need to write the code or just select folder and it create a web gallery for you..
Adobe Photoshop cs2 have this feature built in

rize | March 1st, 2009 @ 2:23 am

nice post! I can’t wait to use it!

Jeremy | March 14th, 2009 @ 11:11 am

everything works fine, but I have the gallery in a table, all other pages are centered on site, but this one comes in on left. Any idea on how to center it? I realize this may be a stupid question, but inquiring minds would love to know. It works in opera, not firefox or safari…not sure about IE. Any ideas?

brad | March 15th, 2009 @ 9:45 pm

Nice, twitterd for my tweeple.

SB | March 16th, 2009 @ 5:19 am

very good, thanks

sivas | March 18th, 2009 @ 3:35 am

[...] 24. Auto Generating Gallery [...]

[...] 22. Script and Style Auto-Generated Photo Gallery [...]

my only concern with this is that not one of those thumbnails contains alt text. How are you dealing with accessibility?

Tim Wright | March 31st, 2009 @ 8:10 am

[...] 22. Script and Style Auto-Generated Photo Gallery [...]

[...] Script and Style - Auto-Generated Photo Gallery (Demo) [...]

50 Bildergalerien - Andmore.org | March 31st, 2009 @ 9:29 am

[...] 22. Script and Style Auto-Generated Photo Gallery [...]

[...] 22. Script and Style Auto-Generated Photo Gallery [...]