PHP instant gallery maker with thumbnail

this is a file by putting it in a folder containing some images will be displayed as gallery in thumbnail. it will generate thumbnail for the first time only.

later it will grab the thumbnails from it’s cache directory. the class itself and instantiation is in same class. you just need put it in the folder where your images resides.

NO JAILBREAK REQUIRED!

Good Luck!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
<?php
 
/**
 * Directory2Gallery - Gallery maker
 * Do you need to create photo gallery from all the images recursivley kept in
 * different folders? Do you like to filter those files? Well, you can do it rite away!
 * just copy this index.php file and paste it in your desired location. Point your browser to it
 * And see the fun!!
 *
 * This file contains some code used only when you drop this file in any folder to access the
 * folder for viewing as gallery. Optionally you may use jQuery tools overlay or something
 * like that to add overlay effect. Owh by the way NO HTACCESS IS REQUIRED!
 *
 *
 * @package     Directory2Gallery
 * @category    Class
 * @license     LGPL
 * @since       Version 1.3
 * @author      Nurul Ferdous <nurul.ferdous@gmail.com>
 * @link        http://dynamicguy.com
 * @todo        Overlay implementation
 * @see         http://flowplayer.org/tools/demos/overlay/index.html
 *
 */
class Dir2Gallery
{
 
    private $_limit;
    protected $_randomized;
    protected $_maxWidth, $_maxHeight;
 
    /**
     *
     * @param Array $whiteLists Allowed file extensions
     * @param Integer $limit
     * @param Boolean $randomize whether to randomize the resultset or not
     * @param Integer $maxWidth maximum width of an image
     * @param Integer $maxHeight maximum height of an image
     */
    public function __construct($whiteLists, $limit, $randomize, $maxWidth, $maxHeight)
    {
        $this->_init($limit, $randomize, $maxWidth, $maxHeight);
        $this->makeGallery($whiteLists);
    }
 
    /**
     * Initializing common resources
     *
     * @param Integer $limit
     * @param Boolean $randomize whether to randomize the resultset or not
     * @param Integer $maxWidth maximum width of an image
     * @param Integer $maxHeight maximum height of an image
     *
     */
    private function _init($limit, $randomize, $maxWidth, $maxHeight)
    {
        $this->_limit = $limit;
        $this->_randomized = $randomize;
        $this->_maxWidth = $maxWidth;
        $this->_maxHeight = $maxHeight;
    }
 
    /**
     * Display the Galllery. All the magic happens here!
     *
     * @param Array $whiteLists Allowed file extensions
     * @return Void Alternatively you can return the value like this: {return $html;}
     */
    public function makeGallery($whiteLists)
    {
        $images = $this->_getCleanedFiles($whiteLists);
        if ($images) {
            $html = '<ul>';
            foreach ($images as $image) {
                $html .= '<li style="display:inline;margin: 5px 10px 5px 0">';
                $html .= $this->_scaleImage($image['path'], $this->_maxWidth, 100, $image['name']);
                $html .= '</li>';
            }
            $html .= '<ul>';
        } else {
            $html = "Oops! our bad!! you haven't put any files in your directory. Please feed'em some files dude!!!";
        }
        echo $html;
    }
 
    /**
     * Scale the image proportionately for the thumbnail image
     *
     * @param String $p Image path
     * @param Integer $mw Maxumum width for an image
     * @param Integer $mh Maxumum height for an image
     * @param String $title
     * @return String
     */
    private function _scaleImage($originalImage, $toWidth, $toHeight, $title = '')
    {
        // Get the original geometry and calculate scales
        list($width, $height) = getimagesize($originalImage);
        $xscale = $width / $toWidth;
        $yscale = $height / $toHeight;
 
        // Recalculate new size with default ratio
        if ($yscale > $xscale) {
            $new_width = round($width * (1 / $yscale));
            $new_height = round($height * (1 / $yscale));
        } else {
            $new_width = round($width * (1 / $xscale));
            $new_height = round($height * (1 / $xscale));
        }
 
        $dir = 'cache/' . $toWidth . 'x' . $toHeight;
        $filepath = $dir . strstr($originalImage, '/');
        $ext = strtolower(strstr($filepath, '.'));
 
        // Resize the original image
        $imageResized = imagecreatetruecolor($new_width, $new_height);
        if ($ext == '.jpg') {
            $imageTmp = imagecreatefromjpeg($originalImage);
        } elseif ($ext == '.gif') {
            $imageTmp = imagecreatefromgif($originalImage);
        }
 
        imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
 
        if (!file_exists($dir)) {
            if (!@mkdir($dir, 0777, true)) {
                $error = error_get_last();
                echo 'Error: unable to write in ' . $filepath . '. make sure that ' . getcwd() . ' has write permission';
                exit(0);
            }
        }
        if (!file_exists($filepath)) {
            if ($ext == '.jpg') {
                imagejpeg($imageResized, $dir . strstr($originalImage, '/'));
            } elseif ($ext == '.gif') {
                imagegif($imageResized, $dir . strstr($originalImage, '/'));
            }
        }
        imagedestroy($imageTmp);
        return("<a href='{$originalImage}'><img style='padding:4px;border:1px solid #ddd;' src='{$originalImage}' alt='{$title}' title='{$title}' width='{$new_width}' height='{$new_height}' /></a>");
    }
 
    /**
     * A little house keeping :)
     *
     * @param Array $filter the whitelist of allowed files
     * @return Array
     */
    private function _getCleanedFiles($filter)
    {
        $dirtyArray = $this->_directoryToArray('.', true);
        foreach ($dirtyArray as $data) {
            if (is_file($data)) {
                // get the file extension by taking everything after the last dot
                $extension = end(explode('.', $data));
 
                // if there is no filter set or the filter is set and matches
                if (in_array($extension, $filter)) {
                    // add the file details to the file list
                    $cleanArray[] = array(
                        'path' => $data,
                        'name' => end(explode('/', $data)),
                        'extension' => $extension,
                        'size' => filesize($data),
                        'mime' => mime_content_type($data)
                    );
                }
            }
        }
        return $cleanArray;
    }
 
    /**
     *
     * @param String $directory the directory path
     * @param Boolean $recursive whether to grab files recursively or not
     * @return Array
     */
    private function _directoryToArray($directory = '.', $recursive = TRUE)
    {
        $array_items = array();
        if ($handle = opendir($directory)) {
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != ".." && $file != 'cache') {
                    if (is_dir($directory . "/" . $file)) {
                        if ($recursive) {
                            $array_items = array_merge($array_items, $this->_directoryToArray($directory . "/" . $file, $recursive));
                        }
                        $file = $directory . "/" . $file;
                        $array_items[] = preg_replace("/\/\//si", "/", $file);
                    } else {
                        $file = $directory . "/" . $file;
                        $array_items[] = preg_replace("/\/\//si", "/", $file);
                    }
                }
            }
            closedir($handle);
        }
 
        if ($this->_randomized)
            shuffle($array_items);
 
        if (!$this->_limit)
            $this->_limit = count($array_items);
 
 
        return array_slice($array_items, 0, $this->_limit);
    }
 
}
 
// initializing the class
$gallery = new Dir2Gallery(array('GIF', 'jpg', 'jpeg', 'gif', 'png'), null, true, 100, 100);
 
 
/* End of file index.php */
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Identi.ca
  • Posterous
  • Technorati
  • Tumblr
  • Twitter
  • HackerNews
  • LinkedIn
  • Live
  • Netvibes
  • Reddit
  • StumbleUpon
  • Yahoo! Bookmarks
  • Yahoo! Buzz

Related posts:

  1. Create your IM bot for gtalk/jabber/aim/yahoo with imified API

8 Responses to “PHP instant gallery maker with thumbnail”

  1. The cache feature makes it more usable. :)

  2. Where can I find some more information relating to this?

Leave a Reply