Being a lazy Perl programmer, I have hacked together a script that will
automatically build a site.images hash from the images in a given
directory. It also calculates the image dimensions using Image::Info.
Hopefully this code could eventually be used to dynamically calculate
this info.
Enjoy!
William
#!/usr/bin/perl -w
#===============================================================================
#
# FILE: build_images_hash.pl
#
# USAGE: ./build_images_hash.pl <dir>
#
# DESCRIPTION: This script analyses the files in the current directory to
# create a hash of data that can be inserted into a TT2Site template. It also
# prints to STDERR lines that can be inserted into your templates for
# including the files.
#
# LIMITATIONS: Currently only processes jpg, gif, or png.
# Does do recurse into subdirs.
# Does not catch shortname duplications
#
# OPTIONS: <dir> is directory name to be processed
# REQUIREMENTS: Image::Info
# BUGS: ---
# NOTES: ---
# AUTHOR: William McKee (WMCKEE), <william@knowmad.com>
# COMPANY: Knowmad Services Inc.
# VERSION: 1.0
# CREATED: 01/26/2005 02:16:03 PM EST
# REVISION: ---
#===============================================================================
use strict;
use constant DEBUG => 1;
use Image::Info qw(image_info dim);
use File::Basename;
use Cwd;
use Data::Dumper;
my $dirname = $ARGV[0] || ".";
my @suffixlist = qw(jpg png gif);
my $imagelist;
opendir(DIR, $dirname) or die "can't opendir $dirname: $!\n";
while (defined(my $file = readdir(DIR))) {
my ($name,$path,$suffix) = fileparse($file,@suffixlist);
next unless $suffix;
warn "Processing $file...\n" if DEBUG;
# Initialize hash
my $data = {};
# shortname, alt, title
($data->{'shortname'}) = $name =~ /^(.+?)[_.-]/;
$data->{'alt'} = ucfirst($name);
chop($data->{'alt'});
$data->{'alt'} =~ s/_/\ /g;
$data->{'title'} = $data->{'alt'};
# src
$data->{'src'} = "\$site.url.images/$file";
# get dimensions
my $cwd = cwd();
my $fullpath = "$cwd/$dirname/$file";
die "File not found: $fullpath" unless -e $fullpath;
my $info = image_info($fullpath) || die "Unable to read $fullpath: $!";
my $wh = dim($info) || die "Unable to retrieve dimensions: $!";
my ($w, $h) = dim($info) or die "Unable to retrieve dimensions: $!";
($data->{'width'}, $data->{'height'}) = ($w, $h);
print Dumper($data) if DEBUG >= 2;
push @{$imagelist}, $data;
}
closedir DIR;
# Now print the results for site.images list
foreach my $img (@$imagelist) {
print $img->{'shortname'} . " = {\n";
print 'src = "' . $img->{'src'} . "\"\n";
print 'alt = "' . $img->{'alt'} . "\"\n";
print 'title = "' . $img->{'title'} . "\"\n";
print "width = " . $img->{'width'} . "\n";
print "height = " . $img->{'height'} . "\n";
print "}\n";
# And print to STDERR some sample code to use the images
my $short = $img->{'shortname'};
warn qq~[%- INCLUDE util/image image=site.image.$short | trim -%]\n~;
}