FAGZAL's blog

Channels : ALL    Perl 5  (2)   PET  (2)   Misc.  (1)   Perl-2-PHP  (1)  
http://fagzal.syntaxpoint.com/blog/t207
2007, November 19., 23 h

The task: get an image file, and resize it so that the resulting image (thumbnail) fits in a predefined rectangle without its proportions distorted. We should be able to handle as many image formats as possible.

Without much ado, let's see the code first.

Basic Perl Thumbnail Generator

use strict;      
use Image::Magick;   

# define dimensions, the source and destionation files
my ($width$height$infile$outfile) = (160,160'./source.jpg'
   './thumb.png');

# create object, read source image
my $im = Image::Magick->new;
my $read = $im->Read($infile);
$read && die($read);

# get ORIGINAL width and height
my ($w$h) = $im->Get('width','height');
print "Read: $infile. Dimensions: $w x $h\n";

# Find proportions, calcluate new width and height
my ($neww$newh);
if ($w/$h > $width/$height) {
   $neww = $width;
   $newh = int($h * ($neww/$w));
else {
   $newh = $height;
   $neww = int($w * ($newh/$h));
}
print "New size: $neww x $newh\n";

# Scale image, write out
$im->Resize('width' => $neww'height' => $newh);
$im->Write($outfile);
print "Done.\n";


This is a very much simplified code with a minimal set of "features". We use an image manipulator module called ImageMagick, which is one of the best free image libraries (it's a library written in C, the CPAN module we use is "only" a module to bind Perl functions to C functions).

We read in the image, calculate the new dimensions, then resize and write out the resultin image. We resize even whe it is not mandatory, i.e. if the source image is actually smaller then the one we create.

Note: AFAIK ImageMagick can create a thumbnail with one function call. Let's not worry about that now
 

Direct URL of this entry : http://fagzal.syntaxpoint.com/blog/b179
Number of comments:0


See GALLERY»

Perl 5
entries
1. Perl blog - what's this?
   2007, November 19., 20h
2. First recipe - creating thumbnails
   2007, November 19., 23h

Archive
rss newsfeed icon
Advertisement

Title: En la casa de mi Padre
Visited: 860
Uploaded at: