Using Image::Magick

The following script takes an uploaded image, and write out 3 images: the master, the image scaled to 200x200px and a thumbnail 75x75px as GIFs and puts a border on them.


#!/usr/bin/perl

use Image::Magick;
use CGI;
$query = new CGI;
$image = $query->param('image');
$dir        = '/var/www/html/imagemagick';
$dest_dir   = "$dir/dest";
$source_dir = "$dir/source";

$image =~ s#.*/##  if $image =~ m#/#;
$image =~ s#.*\\## if $image =~ m#\\#;

open BOB, ">$source_dir/$image" or die ($!);
binmode BOB;
$fh = $query->upload('image');
while (<$fh>) {
    print BOB;
}
close BOB;

$imgObj = Image::Magick->new;
$master = Image::Magick->new;
$status = $imgObj->Read("$source_dir/$image");
$status = $master->Read("$source_dir/$image");

# Get image dimensions..
#
$width  = $imgObj->Get('width');
$height = $imgObj->Get('height');

# Do the medium image first, no alterations to the master image, 
# and then do the thumbnail last.
#
if ($width < $height) {
    $x = 200;
    if ($width < 200) { $y = $height + ($width + 200); }
    else          { $y = $height - ($width - 200); }
    $imgObj->Scale("${x}x$y");
    $height = $imgObj->Get('height');
    $crop_y = ($height - 200) / 2;
    $imgObj->Crop(height=>'200',y=>"$crop_y");
}
else {
    $y = 200;
    if ($height < 200) { $x = $width + ($height + 200); }
    else           { $x = $width - ($height - 200); }
    $imgObj->Scale("${x}x$y");
    $width  = $imgObj->Get('width');
    $crop_x = ($width - 200) / 2;
    $imgObj->Crop(width=>'200',x=>"$crop_x");
}

# name the original, normal and thumbnail
#
$write_name = $write_name_thumb = $write_name_orig = $image;
$write_name       =~ s#\..*#_reg.gif#i;
$write_name_thumb =~ s#\..*#_th.gif#i;
$write_name_orig  =~ s#\..*#_orig.gif#i;

# Place border around the image
#
#$imgObj->Border(width=>'4',height=>'4',color=>'FF0000');
$imgObj->Border(geometry=>'8x4', fill=>'black' );
$imgObj->Set(magick=>'GIF89a');

$annotate = $query->param('annotate');
if ( $annotate ) {
    $imgObj->Annotate( text=>$annotate, font=>'Helvetica', pointsize=>20, fill=>'black', antialias=>'True',
    x=>40, y=>20 );
}

#$status = $imgObj->Write("gif:$dest_dir/$write_name");
$status = $imgObj->Write("$dest_dir/$write_name");

# Note, border gets scaled for the thumbnail
#
#$imgObj->Scale('75x75');
$imgObj->Roll( x=> 50, y=> 50 );
$status = $imgObj->Write("gif:$dest_dir/$write_name_thumb");
undef($imgObj);

# Write the master out - dubious, but maybe good for knowing
# it has been processed
#
$master->Set(magick=>'GIF89a');
$status = $master->Write("$dest_dir/$write_name_orig");
undef($master);

# output to your heart's content here...

exit;


<< Back to OC-PM