Currently Browsing: Home » Create a Simple Picture Gallery using PHP

Create a Simple Picture Gallery using PHP

In this post I will show you how to create a simple picture gallery using PHP. This will go through all the pictures in a directory; if a thumbnail does not exist for it, create one for it; and display the thumbnail on a page with the ability to show the full sized pictures. I am going to use the PHP GD library, so make sure that your web server has the GD Library enabled.

View a Demo Download the Files

First of all, you can check if you have the GD Library enabled by creating a file with the contents:


<?php phpinfo(); ?>

If you can find ‘gd’, then the GD library is enabled.

Let’s start with a simple XHTML template:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UFT-8" />
<title>Pictures</title>
</head>
<body>

</body>
</html>

For the purposes of this tutorial, we will use the popular Lightbox Javascript Image Gallery Overlay, so let’s import that now.

You can download the files from the linked page. It specifies that we need to add the CSS and JS files, so let’s put the CSS in the head and the Javascript in the bottom.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UFT-8" />
<link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
<title>Pictures</title>
</head>
<body>

<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
<script type="text/javascript" src="js/lightbox.js"></script>
</body>
</html>

Now comes the PHP. Let’s start out with some settings and a method called getPictures().


	# SETTINGS
	$max_width = 100;
	$max_height = 100;

	function getPictures() {
		global $max_width, $max_height;
	}

We have the line global $max_width, $max_height; to make sure we’re working with the settings. You can set these to whatever you want, but for the purposes of this demonstration, we will used 100px by 100px.

Then we need to open the directory.


	if ( $handle = opendir(".") ) {
		$lightbox = rand();
		echo '<ul id="pictures">';
		while ( ($file = readdir($handle)) !== false ) {
			if ( !is_dir($file) ) {
				// More code goes here
			}
		}
		echo '</ul>';
	}

This loops through the files and makes sure only to work with actual files. The next step would be to determine what kind of image we’re working with. Since the GD library only supports JPG, PNG, and GIF formats, we shall assume those are the only extensions that are images. This little snippet gets the extension, and if it’s not a picture type, we move on. We’ll define the getPictureType($ext) method a bit later.


	$split = explode('.', $file);
	$ext = $split[count($split) - 1];
	if ( ($type = getPictureType($ext)) == '' ) {
		continue;
	}

The next part is to create the folder for the thumbnails if it doesn’t exist, and then to create the thumbnail if it doesn’t exist either:


	if ( ! is_dir('thumbs') ) {
		mkdir('thumbs');
	}
	if ( ! file_exists('thumbs/'.$file) ) {
		if ( $type == 'jpg' ) {
			$src = imagecreatefromjpeg($file);
		} else if ( $type == 'png' ) {
			$src = imagecreatefrompng($file);
		} else if ( $type == 'gif' ) {
			$src = imagecreatefromgif($file);
		}
		if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
			$newW = $oldW * ($max_width / $oldH);
			$newH = $max_height;
		} else {
			$newW = $max_width;
			$newH = $oldH * ($max_height / $oldW);
		}
		$new = imagecreatetruecolor($newW, $newH);
		imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
		if ( $type == 'jpg' ) {
			imagejpeg($new, 'thumbs/'.$file);
		} else if ( $type == 'png' ) {
			imagepng($new, 'thumbs/'.$file);
		} else if ( $type == 'gif' ) {
			imagegif($new, 'thumbs/'.$file);
		}
		imagedestroy($new);
		imagedestroy($src);
	}

Let's analyze this: after making the directory and checking if the thumbnail doesn't already exist, we create the source image based on the picture type. Then, we calculate the new width and the height. We then create a new image and copy the resampled image to it, then we write out the image based on the picture type. Then, to save memory, we destroy the images.

Now we only need to echo this out.


	echo '<li><a href="'.$file.'" rel="lightbox['.$lightbox.']">';
	echo '<img src="thumbs/'.$file.'" alt="" />';
	echo '</a></li>';

So, in total:


	# SETTINGS
	$max_width = 100;
	$max_height = 100;

	function getPictures() {
		global $max_width, $max_height;
		if ( $handle = opendir(".") ) {
			$lightbox = rand();
			echo '<ul id="pictures">';
			while ( ($file = readdir($handle)) !== false ) {
				if ( !is_dir($file) ) {
					$split = explode('.', $file);
					$ext = $split[count($split) - 1];
					if ( ($type = getPictureType($ext)) == '' ) {
						continue;
					}
					if ( ! is_dir('thumbs') ) {
						mkdir('thumbs');
					}
					if ( ! file_exists('thumbs/'.$file) ) {
						if ( $type == 'jpg' ) {
							$src = imagecreatefromjpeg($file);
						} else if ( $type == 'png' ) {
							$src = imagecreatefrompng($file);
						} else if ( $type == 'gif' ) {
							$src = imagecreatefromgif($file);
						}
						if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
							$newW = $oldW * ($max_width / $oldH);
							$newH = $max_height;
						} else {
							$newW = $max_width;
							$newH = $oldH * ($max_height / $oldW);
						}
						$new = imagecreatetruecolor($newW, $newH);
						imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
						if ( $type == 'jpg' ) {
							imagejpeg($new, 'thumbs/'.$file);
						} else if ( $type == 'png' ) {
							imagepng($new, 'thumbs/'.$file);
						} else if ( $type == 'gif' ) {
							imagegif($new, 'thumbs/'.$file);
						}
						imagedestroy($new);
						imagedestroy($src);
					}
					echo '<li><a href="'.$file.'" rel="lightbox['.$lightbox.']">';
					echo '<img src="thumbs/'.$file.'" alt="" />';
					echo '</a></li>';
				}
			}
			echo '</ul>';
		}
	}

Now remember that we still need to define getPictureType($ext).


	function getPictureType($ext) {
		if ( preg_match('/jpg|jpeg/i', $ext) ) {
			return 'jpg';
		} else if ( preg_match('/png/i', $ext) ) {
			return 'png';
		} else if ( preg_match('/gif/i', $ext) ) {
			return 'gif';
		} else {
			return '';
		}
	}

Now, in the HTML, we need to make sure that we call <?php getPictures(); ?>. Add in some basic CSS and the HTML is:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UFT-8" />
<title>Pictures</title>
<link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
<style type="text/css">
#pictures li {
	float:left;
	height:<?php echo ($max_height + 10); ?>px;
	list-style:none outside;
	width:<?php echo ($max_width + 10); ?>px;
	text-align:center;
}
img {
	border:0;
	outline:none;
}
</style>
</head>
<body>

<?php getPictures(); ?>

<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
<script type="text/javascript" src="js/lightbox.js"></script>
</body>
</html>

And that’s it.

Next on this topic: Simple PHP Gallery Pagination

Tags: ,

This entry was posted on Friday, March 13th, 2009 at 17:32:26. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

Want to be notified when someone replies? Subscribe to this post's comment RSS feed.
Any field marked with a * is required.