Products | Scripts | Services | Tutorials | Books | Links | Contact | Bulletin Board

Docs and Tutorials

Uploading scripts | Setting up Apache on NT | Converting MP3 files | Install Modules from CPAN
Optimizing mod_perl | Fight Spam - conceal your emails | Build thumbnails in batch mode

How to make thumbnails of your images using a Perl script

You can use ImageMagick. It is a wrapper for a very good image handling module, with the product home page at: http://www.imagemagick.org/. We strongly suggest you read all the documentation on their page, and take your time at installing it.

On the ImageMagick product page you will find a link to instructions of how to install Perl::Magick, the interface to any script that will use this application: http://www.imagemagick.org/www/perl.html

Here is an example subroutine that will help you build your code into the shop, or adapt it to any other script you want:

sub _MakeThumbnails {
  use Image::Magick;
my ($x, @FullImages);
my $ProductDir = shift || "/var/www/html/images/shops/city/products";
# you can use percents my $Ratio = shift || ''; # you can pass a percentage like: 50%
# or you can use the following limits format
my $MaxHeight = shift || ''; # a number in pixels, i.e.: 100
my $MaxWidth = shift || ''; die 'Provide some parameter to define thumbnail sizes' if ! $Ratio && ! ($MaxHeight && $MaxWidth); # We read all the files in that directory and we select # all the images that are not already thumbnails. Feel free to # customize the search here to match your thumbnail naming convention. # ...you DO have a naming convention, right? :) opendir(THISDIR, $ProductDir);
my @Items = grep(!/^\.\.?$/,readdir(THISDIR));
foreach $x(@Items) {push(@FullImages, $x) if $x !~ /_thmb\.\w+$/oi}
closedir(THISDIR); my $p = new Image::Magick;
foreach $x(@FullImages) {
next if $x !~ /^(.*)(\..+)$/;
my $Target = $ProductDir.'/'.$1.'_thmb'.$2;
$p->Read("$ProductDir/$x");
my ($w, $h) = $p->Get('width', 'height');
$h = 1 if ! $h;
$w = 1 if ! $w;
if ($MaxHeight || $MaxWidth) {
my $HR = $MaxHeight / $h;
my $WR = $MaxWidth / $w;
$Ratio = $HR && $HR < $WR ? $HR : $WR;
} $w = $Ratio =~ /\s*(.*)\s*\%/o ? int($w * $1 / 100) : int $w * $Ratio;
$h = $Ratio =~ /\s*(.*)\s*\%/o ? int($h * $1 / 100) : int $h * $Ratio;
$p->Resize(
width => $w,
height => $h,
);
$p->Write($Target);
} }