#!/usr/bin/perl
##################################
# By: Ventz Petkov               #
# Date: 12-09-05                 #
# Image Resizer + HTML Generator #
##################################
use warnings;
use strict;

# Need the lib for (gd-1.8.3) and (p5-GD-1.41p1)
use lib "/usr/local/libdata/perl5/site_perl/sparc64-openbsd/";

use GD;
use Image::Size;
use File::Find::Rule;

if (@ARGV != 2) {
    print "\t\tUsage: ./imageresize.pl <output_directory> <percent_to>\n";
    print "\t\tEx: ./imageresize.pl /home/iodita/public_html/pics 50\n"; exit();
}

my $outDir = $ARGV[0];
unless(-d $outDir and -e $outDir) {
    mkdir $outDir;
}
my $percent = ($ARGV[1]) * 0.01;
my $rule = File::Find::Rule->file->name("*.jp*")->start( "." );
open(HTML, ">$outDir/index.html");
print HTML "
<html>
<head><title>Auto-Generated small_ Images</title></head>
<body>
<center><h1>Auto Generated Images</h1></center>
";
while(my $fileName = $rule->match) {
    my ($width, $height) = imgsize($fileName);
    my ($outWidth, $outHeight) = ($percent * $width, $percent * $height);

    # The following bellow is simplly HELL to reconstruct if screwed up.
    # It must've taken me a good 15 minutes to get this straighten out.
    # DON'T TOUCH BELOW THIS #
    ##########################
    my $destimage = GD::Image->new($outWidth,$outHeight);
    my $srcimage = GD::Image->new($fileName);
    my ($destX, $destY) = (0,0); my ($srcX, $srcY) = (0,0);
    my ($destW, $destH) = ($outWidth,$outHeight); my ($srcW, $srcH) = ($width,$height);
    $destimage->copyResized($srcimage, $destX, $destY, $srcX, $srcY, $destW, $destH, $srcW, $srcH);
    ##########################
    # DON'T TOUCH ABOVE THIS #

    #if($fileName =~ s/\/(.*)$/$1/) { $fileName = $1; }
    if($fileName =~ s/\//-/g) { }
    if($fileName =~ s/\%20/_/g) { }
    print "$outDir/small_$fileName\n";
    open(FH, ">/$outDir/small_$fileName");
    print FH $destimage->jpeg();
    print HTML "<img src=\"small_$fileName\" border=0><br><hr>";
    close(FH);
}
print HTML "
</body>
</html>
";
print "Generated HTML...$outDir/index.html\n";
close(HTML);
