Lateral Code
A Web Design Blog Focused on Code and Technology
Currently Browsing: Home » Create a Simple Picture Gallery using PHP
Create a Simple Picture Gallery using PHP
By Patrick Lin
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
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.
38 Responses to “Create a Simple Picture Gallery using PHP”
Leave a Reply
Really nice tutorial. However, the download didnt include the css or js files for the lightbox
Nice and fresh gallery php generator.
I would like to create crop thumbnails to 100px x 100px square, what I must to do? Can you help me please!!!
@Charlie: My apologies, a fixed version has been uploaded.
@kloc: I will make another post explaining different aspects of the GD Library. You can subscribe to our RSS Feed so you can catch it when it goes up.
Reading images from a directory is a useful snippet to have around, but this implementation is really messy.
For customization purposes (and I don’t just mean for people downloading your demo for their own purposes; I mean if you were to need to reuse this in a different manner for a different client or project), this code is a nightmare, since everything is lumped into one function.
This could easily be broken up into component functions or, better, an object-oriented approach that would simplify each step to an easily identifiable snippet or method (i.e. loadFilesFromDir(), createThumbnail(), etc.).
Obviously, this isn’t necessary, but it’s good coding practice. You’ve got all sorts of logic tangled up in a single function, which makes for really tough maintenance if you walk away and try to reuse this after a lengthy period of time.
Overall, though, this is a good intro to the GD library. Keep it up!
Thanks for tutorial ! Great post
some pagination added to this would make it a perfect tutorial for me personally
@KDM:
Stay tuned for a followup post to this, showing how to add some simple pagination.
Thank you for your nice step-by-step tutorial. I am just a beginner @ PHP and I windered how you could sequence the image by their filenames (eg: 2182.JPG is followed by 2183.JPG, 2184.JPG, 2190.JPG etc.).
Is there a place to set descending?
Hello kab,
On certain webservers the
readdirmethod does read in order, but on others it does not. I will write an article about this. You can subscribe to our RSS feed so you can see when it comes out, or you can check back here later.Regards,
Patrick
Thanks, I looking forward to this article … so: How many days till Christmas?
Hi Patrick,
I had another question regarding this nice tutorial if you don’t mind.
And sorry again for me being a complete PHP noob.
Is it possible to address different directories to get the images from?
Cause right now all the images are being taken from the directory the index is in.
For example, can i use the same “simple php gallery” code twice on different pages to address different image folders?
So “page1.php” gets the images from folder “/imagesA”
And “page2.php gets different images located in “/imagesB”
Is there a line of code to alter so it changes the directory it gets the images from?
thanks
This line right here:
if ( $handle = opendir(".") ) {“.” means the current directory. You can change it to say “imagesA” or “imagesB”.
This doesn’t seem to be working:(
I took a screenshot:
http://cmdstud.khlim.be/~sverryt/other/phpgallery.jpg
I’ve used your files and images, and they work fine if i keep the “.” and leave the images in the root.
But when I put them in “/imagesA” and change the code it gives me these errors.
What’s weird is it act’s like it can’t find the files but DOES know the filename.
No, you don’t specify “/imagesA”. If you put that slash at the beginning that takes you to the root directory. Just put “imagesA” to keep to the local directory.
I tried that, just like in my screenshot(on the bottom-left),
and afterwards i tried “/imagesA” and even the full adress “http://localhost/phpgallery/imagesA” but i can’t get it to work, i keep getting the error messages.
If you can’t help me it’s no prob, I appreciate the help you gave me so far, so don’t worry if you can’t find a solution I’ll crack my own brain to work around the prob:)
happy April’s fool’s day btw, and placing the fish on the backs of unsuspecting people is a tradition here in Belgium too, although you don’t see it very often anymore;)
Ah, I believe I know the problem now. In your loop, find all the times that you access
$filemake it"imagesA/".$file. For example,if ( ! is_dir("imagesA/".$file ) )The problem is that when you call
$fileby itself, it tries to access the filename in the current directory, but it needs to access the one in"imagesA".Hope this helps
I currently have a paper fish stuck to my shoulder because my friend couldn’t access my back because of the backpack I was wearing
(I’m not French, though, it’s just what people that take French at my school do)
Thanks a lot Patrick, this seems to be working great!
Great tut, thanks. Is there a way to ad a title and link to another website for each image?
Great Script. Thanks.
Does anyone know how to put a sortby on this script?
My images are named 001.jpg, 002.jpg etc.. but display in a random order.
Any help would be really appreciated..
Thanks.
Johnnie,
Your problem was covered in another article here, Reading directories in sequence in PHP.
Patrick
Fantastic!
Thank you
Hi there!
I am a total php nerd
and I am trying to use your gorgeous script! I also have almost the same problem with the directory as Deca. The gallery.php [index.php] is in my root directory, but I want to handle the images like that:
Thumbs: domain.com/images/gallery/thumb_[filename].jpg
Pictures: domain.com/images/gallery/detail_[filename].jpg
Is there are possibility to transform your php code (also combining the “next page” / “prev page” addition) so that it works with that style? And can I say that one row should contain X thumbs/pictures and then a next row begins?
I am so sorry for my bad English, I really hope you can help me!!!
im a beginner in php i need this code badly, and i dont know what value will i put on $page=$_GET['page']; to display the images just like on the demo–
$page=$_GET['(what value should i put on this part?)'];
please help me, im working on my thesis right now, its a tourism website for our municipality here in the philippines..
kindly email me at adamcanape@yahoo.com..
please please, i realy need help on this…
hi patrick,
nice tutorial…
can you please explain the same thing by using database…
i got problem please see my code
<a href=”admin/pictures/” rel=”lightbox” title=”my caption”><img src=”admin/pictures/” width=”143″ height=”116″ />
iam not getting pagination for the above code how to use next and previos for the above code please tell me..
Thanks in advance
Excellent information. Finding a few such solutions has taken hours in the past.
Thank u.
I am still trying to resolve the problem Deca was having. I understand putting the code in in examples like this:
if ( !is_dir(“gallery”.$file) ) {
$split = explode(‘.’, “gallery”.$file);
but what do you do on problem like this:
if ( ! file_exists(‘thumbs/’.$file) )
or better yet:
imagejpeg($new, ‘thumbs/’.$file);
?? btw you are great for posting this code!!
Hi Patrick,
I just want to ask how can I merge this gallery to my already created page. The code is working on a new created Page. But I just can’t trace how does the image or thumbs goes out on a page. Sorry but I just really need your help.
Thank you.
Macky
I think this is it.
#pictures li {
float:left;
height:px;
list-style:none outside;
width:px;
text-align:center;
}
img {
border:0;
outline:none;
}
but I dont know where to find #pictures in CSS.
Thanks.
Mine works if you have both the image and thumbnail in their folders, but it refuses to convertn an image to a thumbnail if it doesn’t already exist. It’s giving me this….Unable to open ‘thumbs/beefonions.jpg’ for writing: Permission denied in D:\Hosting\4960765\html\PHPGallery\index.php on line 3. That sounds to me like my hosting company doesn’t want to grant write priviledges so it won’t create the thumbnail. Is that it or is it something else I’m missing?
Hi there!
Thank you for sharing with us this pretty work.
well i need to use many different galleries. ondering if it possible to do it with this gallery script? and thank you very much
I’m having the same problem as Deca in trying to make the page 2 access a different set of images (from a different folder (called imagesgallery)) than page 1.
I have added the name of the folder to this line
function getPictures() {
global $page, $per_page, $has_previous, $has_next;
if ( $handle = opendir(“imagesgallery”) ) {
$lightbox = rand();
echo ”;I keep getting the error
This is fine it causes no errors but no change in images?
If I add the folder name in any form I get this error:
$arr = array();
while( !feof( $file ) ) {
$arr[ str_replace( "\n", '', fgets(imagesgallery $file ) ) ] = str_replace( “\n”, ”, fgets( $file ) );
}
Parse error: syntax error, unexpected T_VARIABLE in /Applications/XAMPP/xamppfiles/htdocs/ianjonesphotography.com/gallery.php on line 17
Thank you so much, this is excellent.
looks like i am not the only one with the directory bug,
well i have managed to get it to create the /thumbs/ folder inside images (one i that assigned!) but it will not create the thumbs in it,
if i assign the alt tag as the $file, you can see a link (text ) to the image but then again no thumbs inside the thumbs folder…..
for any one whom wants to see the script modified by me here it is (BTW i am a total noob at PHP)
<?php
# SETTINGS
$max_width = 100;
$max_height = 100;
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 '';
}
}
function getPictures() {
global $max_width, $max_height;
if ( $handle = opendir("./images") ) {
$lightbox = rand();
echo '’;
while ( ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) ) {
$split = explode(‘./images/’, $file);
$ext = $split[count($split) - 1];
if ( ($type = getPictureType($ext)) == ” ) {
continue;
}
if ( ! is_dir(‘./images/thumbs’) ) {
mkdir(‘./images/thumbs’);
}
if ( ! file_exists(‘./images/’.$file) ) {
if ( $type == ‘jpg’ ) {
$src = imagecreatefromjpeg(‘./images/’.$file);
} else if ( $type == ‘png’ ) {
$src = imagecreatefrompng(‘./images/’.$file);
} else if ( $type == ‘gif’ ) {
$src = imagecreatefromgif(‘./images/’.$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, './images/thumbs/'.$file);
} else if ( $type == 'png' ) {
imagepng($new, './images/thumbs/'.$file);
} else if ( $type == 'gif' ) {
imagegif($new, './images/thumbs/'.$file);
}
imagedestroy($new);
imagedestroy($src);
}
echo '‘;
echo ”;
echo ‘‘;
}
}
echo ”;
}
}
?>
Pictures
#pictures li {
float:left;
height:px;
list-style:none outside;
width:px;
text-align:center;
}
img {
border:0;
outline:none;
}
Hi,
Firstly I am totally new to PHP, and I am jumping in the deep end here.
I am trying to get this to work with CakePHP and I am nearly there just have the following 4 error messages:
Warning (2): imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions [APP\views\pages\gallery.ctp, line 54]
Code | Context
$imagedir = “D:\Domains\gdchauffeurs.com\wwwroot/app/webroot/img/gallery/”
$thumbs = “D:\Domains\gdchauffeurs.com\wwwroot/app/webroot/img/gallery/thumbs/”
$max_width = null
$max_height = null
$handle = resource
$lightbox = 8360
$file = “mercname.jpg”
$split = array(
“mercname”,
“jpg”
)
$ext = “jpg”
$type = “jpg”
$src = resource
$oldW = 320
$oldH = 240
$newW = null
$newH = 0
imagecreatetruecolor – [internal], line ??
getPictures – APP\views\pages\gallery.ctp, line 54
include – APP\views\pages\gallery.ctp, line 98
View::_render() – CORE\cake\libs\view\view.php, line 666
View::render() – CORE\cake\libs\view\view.php, line 376
Controller::render() – CORE\cake\libs\controller\controller.php, line 803
PagesController::display() – APP\controllers\pages_controller.php, line 82
Object::dispatchMethod() – CORE\cake\libs\object.php, line 118
Dispatcher::_invoke() – CORE\cake\dispatcher.php, line 227
Dispatcher::dispatch() – CORE\cake\dispatcher.php, line 194
require – APP\webroot\index.php, line 88
[main] – CORE\index.php, line 61
Warning (2): imagecopyresampled(): supplied argument is not a valid Image resource [APP\views\pages\gallery.ctp, line 55]
Code | Context
$imagedir = “D:\Domains\gdchauffeurs.com\wwwroot/app/webroot/img/gallery/”
$thumbs = “D:\Domains\gdchauffeurs.com\wwwroot/app/webroot/img/gallery/thumbs/”
$max_width = null
$max_height = null
$handle = resource
$lightbox = 8360
$file = “mercname.jpg”
$split = array(
“mercname”,
“jpg”
)
$ext = “jpg”
$type = “jpg”
$src = resource
$oldW = 320
$oldH = 240
$newW = null
$newH = 0
$new = false
imagecopyresampled – [internal], line ??
getPictures – APP\views\pages\gallery.ctp, line 55
include – APP\views\pages\gallery.ctp, line 98
View::_render() – CORE\cake\libs\view\view.php, line 666
View::render() – CORE\cake\libs\view\view.php, line 376
Controller::render() – CORE\cake\libs\controller\controller.php, line 803
PagesController::display() – APP\controllers\pages_controller.php, line 82
Object::dispatchMethod() – CORE\cake\libs\object.php, line 118
Dispatcher::_invoke() – CORE\cake\dispatcher.php, line 227
Dispatcher::dispatch() – CORE\cake\dispatcher.php, line 194
require – APP\webroot\index.php, line 88
[main] – CORE\index.php, line 61
Warning (2): imagejpeg(): supplied argument is not a valid Image resource [APP\views\pages\gallery.ctp, line 57]
Code | Context
$imagedir = “D:\Domains\gdchauffeurs.com\wwwroot/app/webroot/img/gallery/”
$thumbs = “D:\Domains\gdchauffeurs.com\wwwroot/app/webroot/img/gallery/thumbs/”
$max_width = null
$max_height = null
$handle = resource
$lightbox = 8360
$file = “mercname.jpg”
$split = array(
“mercname”,
“jpg”
)
$ext = “jpg”
$type = “jpg”
$src = resource
$oldW = 320
$oldH = 240
$newW = null
$newH = 0
$new = false
imagejpeg – [internal], line ??
getPictures – APP\views\pages\gallery.ctp, line 57
include – APP\views\pages\gallery.ctp, line 98
View::_render() – CORE\cake\libs\view\view.php, line 666
View::render() – CORE\cake\libs\view\view.php, line 376
Controller::render() – CORE\cake\libs\controller\controller.php, line 803
PagesController::display() – APP\controllers\pages_controller.php, line 82
Object::dispatchMethod() – CORE\cake\libs\object.php, line 118
Dispatcher::_invoke() – CORE\cake\dispatcher.php, line 227
Dispatcher::dispatch() – CORE\cake\dispatcher.php, line 194
require – APP\webroot\index.php, line 88
[main] – CORE\index.php, line 61
Warning (2): imagedestroy(): supplied argument is not a valid Image resource [APP\views\pages\gallery.ctp, line 63]
Any idea’s?
Thanks
Great Toturial and it work.
But can I create a category for the image. Example if I want to create category for Room A, B, C and D. Example when I click Room A (Hyperlink) it open the thumbs for Room A.
Hey there! Great Tutorial! What about some info on each image ? We can get it from txt file or something …
What if I want to use other type of file beside picture format? Like .doc or .pdf, is there any way to do so?