Creating an image gallery from a folder of images automatically

David Carr

2 min read - 26th Mar, 2012

This tutorial will show you how to quickly create a gallery from a folder of images. Using PHP and making use of image resizing script. Very handy image resizing script available from https://github.com/mindsharelabs/mthumb/blob/master/mthumb.php.

Demo: https://demos.dcblog.dev/galleryfromfolder

Download: https://github.com/daveismynamecom/gallery-from-folder

All images will be loaded into a list, therefore apply some basic styling:

li{
    list-style-type:none;
    margin-right:10px;
    margin-bottom:10px;
    float:left;
}

Next define the image folder

 $dirname = "images/";

Then load all files into an array using a function called scandir to make sure you don't reference default files that exist within the array define an ignore list and pass any files you don't want loaded

$images = scandir($dirname);
$ignore = Array(".", "..");

Then loop through each item array and if it's not contained in the ignore list echo the image to the screen using the mThumb script (in this case I've called the file img.php) pass it the path to the images and also the width of the image the height will be adjusted automatically and set the zoom level 1 is no zoon while 0 is zoomed.

foreach ($images as $curimg){
    if (!in_array($curimg, $ignore)) {
        echo "<li><a href='".$dirname.$curimg."'><img src='img.php?src=".$dirname.$curimg."&amp;w=300&amp;zc=1' alt='' /></a></li>\n";
    }
}

That's it! I've wrapped all images around a link that points to the original image. this is a very basic example but from just a few lines of code I've got an automated image gallery!

The full script:

<!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=iso-8859-1" />
<title>Gallery from Folder Demo</title>
<style type="text/css">
<!--
li{
    list-style-type:none;
    margin-right:10px;
    margin-bottom:10px;
    float:left;
}

-->
</style></head>

<body>

<ul>
    <?php
        $dirname = "images/";
        $images = scandir($dirname);
        shuffle($images);
        $ignore = Array(".", "..");
        foreach($images as $curimg){
            if(!in_array($curimg, $ignore)) {
                echo "<li><a href='".$dirname.$curimg."'><img src='img.php?src=".$dirname.$curimg."&amp;w=300&amp;zc=1' alt='' /></a></li>\n";
            }
        }                 
    ?>
</ul>

</body>
</html>

 

0 comments
Add a comment

Copyright © 2006 - 2024 DC Blog - All rights reserved.