PerlMagick is an objected-oriented
Perl
interface to ImageMagick. Use
the module to read, manipulate, or write an image or image sequence from
within a Perl script. This makes it very suitable for Web CGI scripts. You
must have ImageMagick 5.4.3 or above and Perl version 5.005_02 or greater
installed on your system for either of these utilities to work.
There are a number of useful scripts available to show you the value of
PerlMagick. You can do Web based image manipulation and conversion with
MagickStudio, or use
L-systems to create images of plants using mathematical constructs, and
finally navigate through collections of thumbnail images and select the image
to view with the WebMagick Image Navigator.
You can try PerlMagick from your Web browser at the
ImageMagick Studio. Or, you can see
examples of select PerlMagick functions.
The following instructions for Unix apply only to the unbundled
PerlMagick as obtained from CPAN. PerlMagick is included as a subdirectory
(PerlMagick) of the ImageMagick source distribution, and may be configured
and built using the instructions provided in the ImageMagick distribution's
README.txt file. It is usually most convenient to install PerlMagick as part
of the ImageMagick distribution.
ImageMagick must already be installed on your system. Next,
get the PerlMagick distribution corresponding
to the installed ImageMagick distribution (e.g. PerlMagick 5.39 for ImageMagick
5.3.0) and unpack it as shown below:
gunzip -c PerlMagick-5.39.tar.gz | tar -xvf - cd PerlMagick
Next, edit Makefile.PL and change LIBS and INC to include the appropriate
path information to the required libMagick library. You will also
need paths to JPEG, PNG, TIFF, etc. delegates if they were included with
your installed version of ImageMagick. Build and install it like this:
perl Makefile.PL make make install
For Unix, you typically need to be root to install the software.
There are ways around this. Consult the Perl manual pages for more information.
Windows XP / Windows 2000
ImageMagick must already be installed on your system. Also, the
ImageMagick source distribution for Windows 2000
is required. You must also have the nmake from the Visual C++ or
J++ development environment. Copy \bin\IMagick.dll and \bin\X11.dll
to a directory in your dynamic load path such as c:\perl\site\5.00502
. Next, type
cd PerlMagick copy Makefile.nt Makefile.PL perl Makefile.PL nmake nmake install
Any script that wants to use PerlMagick methods must
first define the methods within its namespace and instantiate an image object.
Do this with:
use Image::Magick;
$image=Image::Magick->new;
The new() method takes the same parameters as SetAttribute
. For example,
$image=Image::Magick->new(size=>'384x256');
Next you will want to read an image or image sequence, manipulate it, and
then display or write it. The input and output methods for PerlMagick
are defined in Read or Write an Image. See
Set an Image Attribute for methods that affect the way an image is read
or written. Refer to Manipulate an Image for a list of
methods to transform an image. Get an Image Attribute
describes how to retrieve an attribute for an image. Refer to
Create an Image Montage for details about tiling your images as thumbnails
on a background. Finally, some methods do not neatly fit into any of the categories
just mentioned. Review Miscellaneous Methods for a list
of these methods.
Once you are finished with a PerlMagick object you
should consider destroying it. Each image in an image sequence is stored
in virtual memory. This can potentially add up to mega-bytes of memory. Upon
destroying a PerlMagick object, the memory is returned for use by
other Perl methods. The recommended way to destroy an object is with
undef:
undef $image;
To delete all the images but retain the Image::Magick object use
@$image = ();
and finally, to delete a single image from a multi-image sequence, use
undef $image->[x];
The next section illustrates how to use various PerlMagick methods
to manipulate an image sequence.
Some of the PerlMagick methods require external programs such as
Ghostscript. This may require an explicit path in your PATH environment
variable to work properly. For example,
$x = $image->Crop(geometry=>'100x100"+1"00"+1"00'); warn "$x" if "$x";
$x = $image->Write('x.png'); warn "$x" if "$x";
The script reads three images, crops them, and writes a single image as a
GIF animation sequence. In many cases you may want to access individual images
of a sequence. The next example illustrates how this is done:
Or suppose you want to convert your color image to grayscale:
$image->Quantize(colorspace=>'gray');
Here we annotate an image with a Taipai TrueType font:
$text = 'Works like magick!'; $image->Annotate(font=>'kai.ttf', pointsize=>40, fill=>'green', text=>$text);
Other clever things you can do with a PerlMagick objects include
$i = $#$p"+1"; # return the number of images associated with object p push(@$q, @$p); # push the images from object p onto object q @$p = (); # delete the images but not the object p $p->Convolve([1, 2, 1, 2, 4, 2, 1, 2, 1]); # 3x3 Gaussian kernel
If %0Nd, %0No, or %0Nx appears in the filename, it is interpreted
as a printf format specification and the specification is replaced with the
specified decimal, octal, or hexadecimal encoding of the scene number. For
example,
image%03d.miff
converts files image000.miff, image001.miff, etc.
You can optionally add Image to any method
name. For example, ReadImage() is an alias for method Read().
Once you create an image with, for example, method
ReadImage() you may want to operate on it. Below is a list of all the image
manipulations methods available to you with PerlMagick. There are
examples of select
PerlMagick methods. Here is an example call
to an image manipulation method:
apply any clipping path information as an image clip mask.
ColorFloodfill
geometry=>geometry, x=>integer, y=>integer
, fill=>color name, bordercolor=>
color name
changes the color value of any pixel that matches the color of the target
pixel and is a neighbor. If you specify a border color, the color value is
changed for any neighbor pixel that is not that color.
geometry=>geometry, x=>integer, y=>integer
, matte=>integer, bordercolor=>color name
changes the matte value of any pixel that matches the color of the target
pixel and is a neighbor. If you specify a border color, the matte value is
changed for any neighbor pixel that is not that color.
MedianFilter
radius=>double
replace each pixel with the median intensity pixel of a neighborhood.
Note, that the geometry parameter is
a short cut for the width and height parameters (e.g.
geometry=>'106x80' is equivalent to width=>106, height=>80
).
You can specify @filename in both Annotate()
and Draw(). This reads the text or graphic primitive instructions from a
file on disk. For example,
The text parameter for methods, Annotate(), Comment(), Draw(), and
Label() can include the image filename, type, width, height, or other image
attribute by embedding these special format characters:
%b file size %d comment %d directory %e filename extension %f filename %h height %m magick %p page number %s scene number %t top of filename %w width %x x resolution %y y resolution \n newline \r carriage return
For example,
text=>"%m:%f %wx%h"
produces an annotation of MIFF:bird.miff 512x480 for an image titled
bird.miff and whose width is 512 and height
is 480.
You can optionally add Image to any method
name. For example, TrimImage() is an alias for method Trim().
Most of the attributes listed above have an analog
in convert. See the documentation for a more detailed
description of these attributes.
Note, that the geometry parameter
is a short cut for the width and height parameters (e.g.
geometry=>'106x80' is equivalent to
width=>106, height=>80).
SetAttribute() is an alias for method Set().
Most of the attributes listed above have an
analog in convert. See the documentation for a
more detailed description of these attributes.
Use method Montage() to create a composite
image by combining several separate images. The images are tiled on the composite
image with the name of the image optionally appearing just below the individual
tile. For example,
Note, that the geometry parameter
is a short cut for the width and height parameters (e.g.
geometry=>'106x80' is equivalent
to width=>106, height=>80).
MontageImage() is an alias for method
Montage().
Most of the attributes listed above
have an analog in montage. See the documentation
for a more detailed description of these attributes.
A blob contains data that directly
represent a particular image format in memory instead of on disk. PerlMagick
supports blobs in any of these image formats
and provides methods to convert a blob to or from a particular image format.
an array of image data in the respective image format
convert an image or image sequence to an array of blobs
BlobToImage
one or more blobs
the number of blobs converted to an image
convert one or more blobs to an image
ImageToBlob() returns the image data in their respective formats. You can
then print it, save it to an ODBC database, write it to a file, or pipe it
to a display program:
The Append() method append a
set of images. For example,
$p = $image->Append(stack=>{true,false});
appends all the images associated with object $image.
By default, images are stacked left-to-right. Set stack to
True to stack them top-to-bottom.
The Average() method averages
a set of images. For example,
$p = $image->Average();
averages all the images associated with object $image.
The Clone() method copies
a set of images. For example,
$p = $image->Clone();
copies all the images from object $q to $p. You can use
this method for single or multi-image sequences.
The Morph() method morphs
a set of images. Both the image pixels and size are linearly interpolated
to give the appearance of a meta-morphosis from one image to the next:
$p = $image->Morph(frames=>integer);
where frames is the number of in-between images to generate. The default
is 1.
Mosaic() creates an mosaic
from an image sequence.
Method Mogrify() is a single
entry point for the image manipulation methods (Manipulate
an Image). The parameters are the name of a method followed by any parameters
the method may require. For example, these calls are equivalent:
Method MogrifyRegion() applies a transform to a region of the image. It
is similar to Mogrify() but begins with the region geometry. For example,
suppose you want to brighten a 100x100 region of your image at location (40,
50):
Ping() is a convenience method that returns information about an
image without having to read the image into memory. It returns the
width, height, file size in bytes, and the file format of the image.
You can specify more than one filename but only one filehandle:
Where parameters is any parameter of the Annotate
method. The return values are
character width
character height
ascender
descender
text width
text height
maximum horizontal advance
Call QueryColor() with no parameters to return a list of known colors names
or specify one or more color names to get these attributes: red, green, blue,
and opacity value.
Call QueryFont() with no parameters to return a list of known fonts or specify
one or more font names to get these attributes: font name, description,
family, style, stretch, weight, encoding, foundry, format, metrics,
and glyphs values.
Call QueryFormat() with no parameters to return a list of known image formats
or specify one or more format names to get these attributes: adjoin, blob
support, raw, decoder, encoder, description, and module.
Use RemoteCommand() to
send a command to an already running display or
animate
application. The only parameter is the name of the image file to display
or animate.
Finally, the Transform()
method accepts a fully-qualified geometry specification for cropping or resizing
one or more images. For example,
$p = $image->Transform(crop=>'100x100');
You can optionally add Image to any method name above. For example,
PingImage() is an alias for method Ping().
All PerlMagick
methods return an undefined string context upon success. If any problems
occur, the error is returned as a string with an embedded numeric status
code. A status code less than 400 is a warning. This means that the operation
did not complete but was recoverable to some degree. A numeric code greater
or equal to 400 is an error and indicates the operation failed completely.
Here is how errors are returned for the different methods:
Methods which
return a number (e.g. Read(), Write()):
$x = $image->Read(...); warn "$x" if "$x"; # print the error message $x =~ /(\d+)/; print $1; # print the error number print 0+$x; # print the number of images read
Methods which
operate on an image (e.g. Resize(), Crop()):
$x = $image->Crop(...); warn "$x" if "$x"; # print the error message $x =~ /(\d+)/; print $1; # print the error number
Methods which
return images (Average(), Montage(), Clone()) should be checked for errors
this way:
$x = $image->Montage(...); warn "$x" if !ref($x); # print the error message $x =~ /(\d+)/; print $1; # print the error number
Here is an example error message:
Error 400: Memory allocation failed
Below is a list of error and warning codes:
Error and Warning Codes
Code
Mnemonic
Description
0
Success
method completed without an error or warning
300
ResourceLimitWarning
a program resource is exhausted (e.g. not enough memory)
305
TypeWarning
A font is unavailable; a substitution may have occurred
310
OptionWarning
a command-line option was malformed
315
DelegateWarning
an ImageMagick delegate returned a warning
320
MissingDelegateWarning
the image type can not be read or written because the appropriate
Delegate is missing
325
CorruptImageWarning
the image file may be corrupt
330
FileOpenWarning
the image file could not be opened
335
BlobWarning
a binary large object could not be allocated
340
StreamWarning
there was a problem reading or writing from a stream
345
CacheWarning
pixels could not be saved to the pixel cache
350
CoderWarning
there was a problem with an image coder
355
ModuleWarning
there was a problem with an image module
360
DrawWarning
a drawing operation failed
365
ImageWarning
the operation could not complete due to an incompatible image
380
XServerWarning
an X resource is unavailable
385
MonitorWarning
there was a problem with prgress monitor
390
RegistryWarning
there was a problem getting or setting the registry
395
ConfigureWarning
there was a problem getting a configuration file
400
ResourceLimitError
a program resource is exhausted (e.g. not enough memory)
405
TypeError
A font is unavailable; a substitution may have occurred
410
OptionError
a command-line option was malformed
415
DelegateError
an ImageMagick delegate returned a warning
420
MissingDelegateError
the image type can not be read or written because the appropriate
Delegate is missing
425
CorruptImageError
the image file may be corrupt
430
FileOpenError
the image file could not be opened
435
BlobError
a binary large object could not be allocated
440
StreamError
there was a problem reading or writing from a stream
445
CacheError
pixels could not be saved to the pixel cache
450
CoderError
there was a problem with an image coder
455
ModuleError
there was a problem with an image module
460
DrawError
a drawing operation failed
465
ImageError
the operation could not complete due to an incompatible image
480
XServerError
an X resource is unavailable
480
MonitorError
there was a progress monitor error
490
RegistryError
there was a problem getting or setting the registry
495
ConfigureError
there was a problem getting a configuration file
The following illustrates how you can use a numeric status code:
$x = $image->Read('rose.png'); $x =~ /(\d+)/; die "unable to continue" if ($1 == ResourceLimitError);
Permission is
hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files ("PerlMagick"), to deal in PerlMagick
without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of PerlMagick,
and to permit persons to whom the PerlMagick is furnished to do so, subject
to the following conditions:
The above copyright
notice and this permission notice shall be included in all copies or substantial
portions of PerlMagick.
The software
is provided "as is", without warranty of any kind, express or implied, including
but not limited to the warranties of merchantability, fitness for a particular
purpose and noninfringement.In no event shall ImageMagick Studio be liable
for any claim, damages or other liability, whether in an action of contract,
tort or otherwise, arising from, out of or in connection with PerlMagick
or the use or other dealings in PerlMagick.
Except
as contained in this notice, the name of the ImageMagick Studio LLC
shall not be used in advertising or otherwise to promote the sale,
use or other dealings in PerlMagick without prior written authorization from
the ImageMagick Studio.