use strict;
use Image::Magick;
require 5.006;

##############################################################################

sub resize_image {

	# Requires $_[0] = path and filename of image to process; $_[1] = size (in pixels) to scale to; $_[2] = base path of output file; $_[3] = "image" or "thumbnail"; $_[4] = base filename of output file (including extension)


	# Retrieve image properties...
	my $q = Image::Magick->new;
	my ($reduction, $new_width, $new_height, $img_width, $img_height, $img_size, $img_depth, $outfile);
	my $image = $q->Read($_[0]);
	($img_width, $img_height, $img_size, $img_depth) = $q->Get('width', 'height', 'filesize', 'depth');


	# Calculate the new width and height...
	if (($img_width > $_[1]) or ($img_height > $_[1])) {
		undef $reduction; undef $new_width; undef $new_height;
		if ($img_width >= $img_height) {
			$reduction = $img_width / $_[1];
			$new_width = $_[1];
			$new_height = ($img_height / $reduction);
			my $fraction = $new_height; $fraction =~ s/\d+(\.\d+)/$1/os;
			if ($fraction >= .5) { $new_height = ceil($new_height); } else { $new_height = floor($new_height); }
		} else {
			$reduction = $img_height / $_[1];
			$new_height = $_[1];
			$new_width = ($img_width / $reduction);
			my $fraction = $new_width; $fraction =~ s/\d+(\.\d+)/$1/os;
			if ($fraction >= .5) { $new_width = ceil($new_width); } else { $new_width = floor($new_width); }
		}


		# Resize the image...
		$q->Scale(width=>$new_width, height=>$new_height);
	}


	# Write the new file to disk...
	if ($_[3] eq "thumbnail") { $outfile = $_[2] . "/thumbnails/" . $_[4]; } else { $outfile = $_[2] . "/" . $_[4]; }
	my $create_image = $q->Write("$outfile");


	# Tidy up...
	my $image = $q->Read($outfile);
	($img_width, $img_height, $img_size, $img_depth) = $q->Get('width', 'height', 'filesize', 'depth');
	undef $q;
	return ($img_width, $img_height, $img_size, $img_depth);

}

##############################################################################