| 1 | package Image::Resize; | ||
| 2 | |||
| 3 | # $Id: Resize.pm,v 1.5 2005/11/04 23:44:59 sherzodr Exp $ | ||
| 4 | |||
| 5 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | 1 | ▶ | use Carp ('croak'); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 7 | 0 | ▶ | use GD; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 8 | |||
| 9 | $Image::Resize::VERSION = '0.5'; | ||
| 10 | |||
| 11 | # Thanks to Paul Allen <paul.l.allen AT comcast.net> for this tip | ||
| 12 | GD::Image->trueColor( 1 ); | ||
| 13 | |||
| 14 | sub new { | ||
| 15 | my ($class, $image) = @_; | ||
| 16 | unless ( $class && defined($image) ) { croak "Image::Resize->new(): usage error"; } | ||
| 17 | my $gd; | ||
| 18 | |||
| 19 | # Thanks to Nicholas Venturella <nick2588 AT gmail.com> for this tip | ||
| 20 | if (ref($image) eq "GD::Image") { | ||
| 21 | $gd = $image; | ||
| 22 | |||
| 23 | } else { | ||
| 24 | unless ( -e $image ) { croak "Image::Resize->new(): file '$image' does not exist"; } | ||
| 25 | $gd = GD::Image->new($image) or die $@; | ||
| 26 | } | ||
| 27 | |||
| 28 | return bless { | ||
| 29 | gd => $gd | ||
| 30 | }, $class; | ||
| 31 | } | ||
| 32 | |||
| 33 | sub width { return ($_[0]->gd->getBounds)[0]; } | ||
| 34 | sub height { return ($_[0]->gd->getBounds)[1]; } | ||
| 35 | sub gd { return $_[0]->{gd}; } | ||
| 36 | |||
| 37 | sub resize { | ||
| 38 | my $self = shift; | ||
| 39 | my ($width, $height, $constraint) = @_; | ||
| 40 | unless ( defined $constraint ) { $constraint = 1; } | ||
| 41 | unless ( $width && $height ) { croak "Image::Resize->resize(): usage error"; } | ||
| 42 | |||
| 43 | if ( $constraint ) { | ||
| 44 | my $k_h = $height / $self->height; | ||
| 45 | my $k_w = $width / $self->width; | ||
| 46 | my $k = ($k_h < $k_w ? $k_h : $k_w); | ||
| 47 | $height = int($self->height * $k); | ||
| 48 | $width = int($self->width * $k); | ||
| 49 | } | ||
| 50 | |||
| 51 | my $image = GD::Image->new($width, $height); | ||
| 52 | $image->copyResampled($self->gd, | ||
| 53 | 0, 0, # (destX, destY) | ||
| 54 | 0, 0, # (srcX, srxY ) | ||
| 55 | $width, $height, # (destX, destY) | ||
| 56 | $self->width, $self->height | ||
| 57 | ); | ||
| 58 | return $image; | ||
| 59 | } | ||
| 60 | |||
| 61 | |||
| 62 | 1; | ||
| 63 | __END__ | ||