#!/usr/bin/perl
#
# creates thumbnails and a html table from pictures on the command line, e.g.
#
#    thumb *.png
#
# requires ImageMagick and PerlMagick
# http://www.simplesystems.org/ImageMagick/www/perl.html
#
# chris@toys.prowokulta.org
#
# See
# http://toys.prowokulta.org/doc/alex/thumb and
# http://toys.prowokulta.org/doc/alex/thumb.html
#

$|=1;


use Image::Magick;

$max=160;
$col=5;
$currpic=0;
$file='thumb.html';
$thumbext=".thumb.jpg";

open (OUT, ">$file");

print OUT "
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"
\"DTD/xhtml1-transitional.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">
<head>
<title>Image Thumbnails</title>
<link rel=\"StyleSheet\" href=\"/style.css\" type=\"text/css\" />
</head>
<body>
<table>
";


IMGLOOP: foreach $name (@ARGV)
{

if ($name =~ m/$thumbext$/ ) 
{ 
  print "$name ignored \n";
  next IMGLOOP; 
} 


if ($currpic % $col == 0)
{
print OUT "
<tr>
";
} 

my($image, $x);

$image=Image::Magick->new;

$x=$image->Read($name);
warn "$x" if "$x";


$w=$image->Get('width');
$h=$image->Get('height');
$d=$image->Get('depth');
$f=$image->Get('format');
$s=$image->Get('filesize');


$outfile = $name;
$outfile =~ s/([^.]*).(\w*)/$1$thumbext/;

print "$name\t$w\tx $h => $outfile\t";

if ($w > $h )
{
#landscape format
$h= int ($h*$max/$w);
$w=$max;
}
else 
{
#portrait format
$w= int ($w*$max/$h);
$h=$max;
}

$x=$image->Resize(geometry=>"${w}x$h");
if ("$x") 
{
warn "$x";
}
else
{
 $currpic++;
}

if (-f $outfile) 
{
 warn "not overwritten!";
}
else 
{
 print "$w\tx $h \n";
 $x=$image->Write($outfile);
 warn "$x" if "$x";
}

@$image = ();

print OUT "
<td>   
<a href=\"$name\"><img src=\"$outfile\" width=\"$w\" height=\"$h\" alt=\"$name\"/></a>
</td>
";

if ($currpic % $col == 0)
{
print OUT "
</tr>
";
} 


}

if ($currpic % $col != 0)
{
print OUT "
</tr>
";
} 


print OUT "
</table>
<a href=\"../\">up</a>
</body>
</html>
";

close (OUT);