#!/usr/local/bin/perl -w #### # # Image thumbnailer # # Copyright 2006, Simon Wistow # Released under the same terms as Perl itself # #### use strict; use Cwd; use Imager; use Template; use File::Basename; use File::Type; use vars qw(@pics); # work out our directory name my ($dir) = (getcwd =~ m!/([^/]+)$!); # create a directory for thumnails unless it already exists my $thumbdir = '.thumbs'; unless (-e $thumbdir && -d $thumbdir) { mkdir $thumbdir || die "Couldn't create a $thumbdir directory : $!\n"; } # construct a new File::Magic object for checking of files my $ft = File::Type->new; # loop through each file passed foreach my $file (@ARGV) { # don't need our selves or dot files next if $file eq $0; next if $file =~ /^\./; # get the type my $type = $ft->mime_type($file); # next if failure (which probably means it's a directory) next unless defined $type; # or if it's not an imgae next unless $type =~ /^image/; # split it up # my ($name, $path, $suffix) = fileparse($file, '\..+$'); # next unless $suffix; # # don't need to thumbnail thumbnails # next if $file =~ /_sm\./; # make the new name my $new = "$thumbdir/$file"; my $pic; # don't thumbnail if we've already one it if (-f $new) { my $img = Imager->new(); # skip if it's not valid unless ($img->open(file=>$new)) { print STDERR "$file - ",$img->errstr(),"\n"; next; } $pic = { file => $file, thumb => $new, sw => $img->getwidth(), sh => $img->getheight(), }; goto PUSH; } # load the image my $img = Imager->new(); # skip if it's not valid unless ($img->open(file=>$file)) { print STDERR "$file - ",$img->errstr(),"\n"; next; } # work out the scaling factor my $w = $img->getwidth(); my $h = $img->getheight(); my $s = 240/$w; # don't scale up if we're smaller than the default $s = 1 if $s > 1; my $sw = $w * $s; my $sh = $h * $s; $pic = { file => $file, thumb => $new, sw => $sw, sh => $sh, }; # thumbnail the pic my $thumb = $img->scale(scalefactor=>$s); #$thumb->filter(type=>'autolevels'); unless ($thumb->write(file=>$new)) { print STDERR "$file - ",$img->errstr(),"\n"; next; } # do the pushing PUSH: print STDERR "$file -> $new\n"; push @pics, $pic; } # print out the page my $template = join "", ; my $tt = Template->new || die "Couldn't load TT\n"; my $vars = { dir => ucfirst $dir, pics => \@pics, }; $tt->process(\$template, $vars) || die $tt->error(), "\n"; __DATA__ [% dir %]
[% FOREACH pic = pics %]

[% END %]

made with ..