A very typical web programming task is to take a directory which contains a bunch of images, and create a thumbnail gallery out of it. The Album module does this very professionally, and an actual industry - TGP sites - is built around this idea.
In theory, it is relatively easy to create an album. All you have to do is to list the directory, get the images, resize them and then display the thumbnails on a (HTML) page with links to the original images. So let's make this easey in practice, too!
Using a few PET built-ins, I am going to show you how to create an album without writing any Perl code - using only 6 lines of code. We will have a page list.pet which lists the thumbnails, and another one called show.pet, which shows the big (original) image.
list.pet
<io:getDir=images dir="html/images" exti="jpg|jpeg" />
[% FOREACH image = images %]
<a href="/show.pet?file=images/${image.file}"><image:thumbnail
maxwidth="100" maxheight="100" file=image.path border="0" /></a>
[% END %]
show.pet
<img src="/${Query.file}" />
That's it! Of course this has no extra HTML, so if you want to make it look nice, you have to put in some CSS & DIVs & TABLEs and whatnot, but this is all the
codig you need.
Now let's go into the details!
First, in order to "run" the above code, you have to load
PET::Util::Image,
PET::Util::IO and set filter
PET::Util::UtilXmlMap in
global.conf.
UtilXmlMap will transfer the above code (of list.pet) to:
[% images = Util.io.getDir('dir' , 'html/images', 'exti', 'jpg|jpeg') %]
[% FOREACH image = images %]
<a href="/show.pet?file=${image.file}">[%
Util.image.thumbnail('file',image.path,'maxwidth',100,
'maxheight',100,'border','0') %]</a>
[% END %]
The first line calls
PET::Util::IO->getDir('dir' => 'html/images', 'exti' => 'jpg|jpeg'), which returns an arrayref of hashrefs, each hash containing a file from directory "html/images". (The directory is relative to BASEPATH if it does not start with a slash.) The 'exti' parameter greps files which have jpg or jpeg extension.
The we iterate through this directory list using FOREACH, and call a thumbnail generator on them.
PET::Util::Image->thumbnail(...) creates the thumbnail image (if it did not exists already), and returns an <img ... /> tag. (The 'border' parameter is unknown by the 'thumbnail' method, so it is simply passed through.) Note that image.path is a TT variable, so it cannot (must not!) be quoted.
We also link to show.pet, which displays the original image by simply accessing the 'file' query parameter.
Simple, isn't it?
