#!/usr/bin/perl -w use strict; use Image::Magick; use File::Find; use Getopt::Long; # Declares defaults my($size, $dir, $exts, $is_percent, $help) = ("foo", './', "bmp gif jpg jpeg mng pcd pcx png tga tiff xpm", 0, 0); # Changes defaults if specified on command line GetOptions ('size=s' => \$size, 'directory=s' => \$dir, 'extensions=s' => \$exts, 'help' => \$help); # Gives help if indicated help() if $help || $size eq "foo"; # Creates a hash of valid image extensions my(@exts) = split(" ", $exts); my(%exts); foreach (@exts) { $_ = lc; $exts{$_} = 1; } # Formats the $size as the max dimension for the shrink() # subroutine later, unless it was given as a percentage. $size = "${size}x$size" unless $size =~ /%$/; # Recurses, starting from within the current directory, # and shrinks every valid pic it can find find (\&get_img, $dir); # Displays help sub help { print < [OPTIONS] Scales down image files in a directory and all of its subdirectories. Required parameter is: -s, --size May be given as a percentage or as a number of pixels. If a percentage is given, the image will be scaled to that percentage. If a number is given, the image will be scaled so that its largest dimension (height or width) is not greater than the given number in pixels. Valid options are: -d, --directory Directory to begin looking for files in. Defaults to: ./ -e, --extensions Only shrink files that end with the given extensions. The list of extensions should be quoted, each extension separated by a space. Valid extensions are all those file types supported by PerlMagick. Defaults to: "bmp gif jpg jpeg mng pcd pcx png tga tiff xpm" -h, --help Display this help message. Examples: shrink.pl -d ~/pics -s 400 -e "jpg gif" Shrinks all .jpg and .gif files in the ~/pics directory and its subdirectories so that no image has a height or width greater than 400 pixels. shrink.pl -s 40% -e "bmp" Shrinks all .bmp files in the current directory and its subdirectories to 40% of their original size. DONE exit; } # If the current item is a file of a valid extension, shrinks it sub get_img() { if (-f) { my($ext) = $_; $ext =~ s/.*\.(.+)/$1/; shrink($_) if $exts{$ext}; } } # Loads the given image and shrinks it to be within the given size or percentage sub shrink() { my($name) = shift; my($img) = new Image::Magick; print "I got to $name!\n"; print $size; $img->Read($name); $img->Resize('geometry' => $size); $img->Write($name); }