#!/usr/bin/perl

# thumbnail, (c) 2001 Darxus@ChaosReigns.com, released under the GPL.
# http://www.ChaosReigns.com/code/thumbnail/
#
# Creates thumbnail images with about 10,000 pixels (equivalent of a 100x100
# image), so thumbnails of all dimensions get the same amount of detail.
#
# If this inspires you to use a similar calculation for resizing images,
# please consider giving me credit.
#
# Useage:
#
#  ./thumbnail file1.jpg file2.gif file3.bmp
#
# This example will create tn_file1.jpg, tn_file2.gif, and tn_file3.bmp.
#
# Requires: imagemagick http://www.imagemagick.org/
#
# v0.1 Apr 18 19:10 original release
# v0.2 Jun 27 13:57 added $pixelcount variable for clarification
# v0.3 Jun 27 14:08 modified algorythm and output for clairification
# v0.4 Jun 27 14:11 only resize image if new size is smaller

$pixelcount = 10000;

for $file (@ARGV)
{
  @fullpath = reverse(split(/\//,$file));
  $fullpath[0] = "tn_".$fullpath[0];
  $newfile = join('/',reverse(@fullpath));
  print "$newfile\n";
  $info = `identify $file`;
  if ($info =~ m#[^ ]+ (\d+)x(\d+)#)
  {
    $x = $1;
    $y = $2;
  } else {
    print "Failed to parse info:$info\n";
  }
  #print "info:$info\n";
  $pixels = $x * $y;
  $newx = int($x / (sqrt($x * $y) / sqrt($pixelcount)));
  $newy = int($y / (sqrt($x * $y) / sqrt($pixelcount)));
  $newpix = $newx * $newy;
  print("${x}x$y=$pixels -> ${newx}x$newy=$newpix\n");
  #print "convert -geometry ${newx}x$newy $file $newfile\n";
  #print "convert -geometry \"${newx}x${newy}\>\" $file $newfile";
  `convert -geometry \"${newx}x${newy}\>\" $file $newfile`;
}
