#!/usr/bin/perl -w 

# thumb.pl - single file thumbing

use GD;
use Getopt::Long;

# error check
die( "Usage: thumb.pl [options] infile outfile" ) if ( scalar(@ARGV) < 2 );
die( "Infile invalid.") if ( !-e $ARGV[-2] );
die( "Can't resample to self.") if ( $ARGV[-2] eq $ARGV[-1] );

# set values
$inFile = $ARGV[-2];
$outFile = $ARGV[-1];

# some options
$thumbSize = 100;
$offset=10;
$pngOut = 0;
$jpegQuality = 75;

# get command line options
my %options = ();
GetOptions (\%options, "size=i", "offset=i","output-png","quality=i");
$thumbSize = $options{"size"}  if ( exists($options{"size"}) );
$pngOut = $options{"output-png"}  if ( exists($options{"output-png"}) );
$jpegQuality = $options{"quality"}  if ( exists($options{"quality"}) );

# lets DO IT
$fullpath = $inFile;
$im = new GD::Image($fullpath);
$outimage = GD::Image->newTrueColor($thumbSize,$thumbSize);

#get dimensions
($curw,$curh) = $im->getBounds();

# calc offset
$offsetPct = $offset / 100;

# get copy dimensions
if ( $curw >= $curh ) {
	# longer horiz than vert
	$size = int(((1.0-($offsetPct*2)) * $curh)+0.5);
	$hoffset = int(($offsetPct * $curh)+0.5);
	$woffset = int((($curw - $size)/2)+0.5);
} else {
	# longer vert than horiz
	$size = int(((1.0-($offsetPct*2)) * $curw)+0.5);
	$woffset = int(($offsetPct * $curw)+0.5);
	$hoffset = int((($curh - $size)/2)+0.5);
}

# resample. and save the shiz!
$outimage->copyResampled( $im, 0, 0, $woffset, $hoffset, $thumbSize, $thumbSize, $size, $size );

open OUTFILE, ">$outFile";
$pngOut ? print OUTFILE $outimage->png : print OUTFILE $outimage->jpeg($jpegQuality);
close OUTFILE;



