PerlMagick Image API for Perl
Installation • Overview • Example Script • Read or Write an Image • Manipulate an Image • Set an Image Attribute • Get an Image Attribute • Compare an Image to its Reconstruction • Create an Image Montage • Working with Blobs • Direct-access to Image Pixels • Miscellaneous Methods • Handling Exceptions• Constant
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 6.5.5 or above and Perl version 5.005_02 or greater installed on your system for PerlMagick to build properly.
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.
Installation
UNIX
Is PerlMagick available from your system RPM repository? For example, on our CentOS system, we install PerlMagick thusly:
yum install ImageMagick-perl
If not, you must install PerlMagick from the ImageMagick source distribution. Download the latest source release.
Unpack the distribution with this command:
tar xvzf ImageMagick.tar.gz
Next configure and compile ImageMagick:
cd ImageMagick-6.9.13-54
./configure -with-perl
make
If ImageMagick / PerlMagick configured and compiled without complaint, you are ready to install it on your system. Administrator privileges are required to install. To install, type
sudo make install
You may need to configure the dynamic linker run-time bindings:
sudo ldconfig /usr/local/lib
Finally, verify the PerlMagick install worked properly, type
perl -MImage::Magick -le 'print Image::Magick->QuantumDepth'
Congratulations, you have a working ImageMagick distribution and you are ready to use PerlMagick to convert, compose, or edit your images.
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
perl Makefile.nt
nmake
nmake install
Running the Regression Tests
To verify a correct installation, type
make test
Use nmake test under Windows. There are a few demonstration scripts available to exercise many of the functions PerlMagick can perform. Type
Use the prove utility to execute a test from the build folder:
prove --blib blib -I `pwd` -bv ./t/read.t
cd demo
make
You are now ready to utilize the PerlMagick methods from within your Perl scripts.
Overview
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;
PerlMagick is quantum aware. You can request a specific quantum depth when you instantiate an image object:
use Image::Magick::Q16;
$image = Image::Magick::Q16->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 mebibytes 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 (in Linux),
$ENV{PATH}' . "='/../bin:/usr/bin:/usr/local/bin';
Example Script
Here is an example script to get you started:
#!/usr/local/bin/perl
use Image::Magick;
my($image, $x);
$image = Image::Magick->new;
$x = $image->Read('girl.png', 'logo.png', 'rose.png');
warn "$x" if "$x";
$x = $image->Crop(geometry=>'100x100+100+100');
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 done:
#!/usr/local/bin/perl
use Image::Magick;
my($image, $p, $q);
$image = new Image::Magick;
$image->Read('x1.png');
$image->Read('j*.jpg');
$image->Read('k.miff[1, 5, 3]');
$image->Contrast();
for ($x = 0; $image->[$x]; $x++)
{
$image->[$x]->Frame('100x200') if $image->[$x]->Get('magick') eq 'GIF';
undef $image->[$x] if $image->[$x]->Get('columns') < 100;
}
$p = $image->[1];
$p->Draw(stroke=>'red', primitive=>'rectangle', points=>20,20 100,100');
$q = $p->Montage();
undef $image;
$q->Write('x.miff');
Suppose you want to start out with a 100 by 100 pixel white canvas with a red pixel in the center. Try
$image = Image::Magick->new;
$image->Set(size=>'100x100');
$image->ReadImage('canvas:white');
$image->Set('pixel[49,49]'=>'red');
Here we reduce the intensity of the red component at (1,1) by half:
@pixels = $image->GetPixel(x=>1,y=>1);
$pixels[0]*=0.5;
$image->SetPixel(x=>1,y=>1,color=>\@pixels);
Or suppose you want to convert your color image to grayscale:
$image->Quantize(colorspace=>'gray');
Let's annotate an image with a Taipai TrueType font:
$text = 'Works like magick!';
$image->Annotate(font=>'kai.ttf', pointsize=>40, fill=>'green', text=>$text);
Perhaps you want to extract all the pixel intensities from an image and write them to STDOUT:
@pixels = $image->GetPixels(map=>'I', height=>$height, width=>$width, normalize=>true);
binmode STDOUT;
print pack('B*',join('',@pixels));
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
Read or Write an Image
Use the methods listed below to either read, write, or display an image or image sequence:
| Method | Parameters | Return Value | Description |
|---|---|---|---|
| Read | one or more filenames | the number of images read | read an image or image sequence |
| Write | filename | the number of images written | write an image or image sequence |
| Display | server name | the number of images displayed | display the image or image sequence to an X server |
| Animate | server name | the number of images animated | animate image sequence to an X server |
For convenience, methods Write(), Display(), and Animate() can take any parameter that SetAttribute knows about. For example,
$image->Write(filename=>'image.png', compression=>'None');
Use - as the filename to method Read() to read from standard in or to method Write() to write to standard out:
binmode STDOUT;
$image->Write('png:-');
To read an image in the GIF format from a PERL filehandle, use:
$image = Image::Magick->new;
open(IMAGE, 'image.gif');
$image->Read(file=>\*IMAGE);
close(IMAGE);
To write an image in the PNG format to a PERL filehandle, use:
$filename = "image.png";
open(IMAGE, ">$filename");
$image->Write(file=>\*IMAGE, filename=>$filename);
close(IMAGE);
Note, reading from or writing to a Perl filehandle may fail under Windows due to different versions of the C-runtime libraries between ImageMagick and the ActiveState Perl distributions or if one of the DLL's is linked with the /MT option. See Potential Errors Passing CRT Objects Across DLL Boundaries for an explanation.
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().
Manipulate an Image
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:
$image->Crop(geometry=>'100x100+10+20');
$image->[$x]->Frame("100x200");
And here is a list of other image manipulation methods you can call:
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,
image->Draw(fill=>'red', primitive=>'rectangle',
points=>'20,20 100,100 40,40 200,200 60,60 300,300');
Is equivalent to
$image->Draw(fill=>'red', primitive=>'@draw.txt');
Where draw.txt is a file on disk that contains this:
rectangle 20, 20 100, 100
rectangle 40, 40 200, 200
rectangle 60, 60 300, 300
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
%c comment
%d directory
%e filename extension
%f filename
%g page geometry
%h height
%i input filename
%k number of unique colors
%l label
%m magick
%n number of scenes
%o output filename
%p page number
%q quantum depth
%r image class and colorspace
%s scene number
%t top of filename
%u unique temporary filename
%w width
%x x resolution
%y y resolution
%z image depth
%C image compression type
%D image dispose method
%H page height
%Q image compression quality
%T image delay
%W page width
%X page x offset
%Y page y offset
%@ bounding box
%# signature
%% a percent sign
\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.
Set an Image Attribute
Use method Set() to set an image attribute. For example,
$image->Set(dither=>'True');
$image->[$x]->Set(delay=>3);
Where this example uses 'True' and this document says '{True, False}', you can use the case-insensitive strings 'True' and 'False', or you can use the integers 1 and 0.
When you call Get() on a Boolean attribute, Image::Magick returns 1 or 0, not a string.
And here is a list of all the image attributes you can set:
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.
Get an Image Attribute
Use method Get() to get an image attribute. For example,
($a, $b, $c) = $image->Get('colorspace', 'magick', 'adjoin');
$width = $image->[3]->Get('columns');
In addition to all the attributes listed in Set an Image Attribute , you can get these additional attributes:
GetAttribute() is an alias for method Get().
Most of the attributes listed above have an analog in convert. See the documentation for a more detailed description of these attributes.
Compare an Image to its Reconstruction
Mathematically and visually annotate the difference between an image and its reconstruction with the Compare() method. The method supports these parameters:
| Parameter | Values | Description |
|---|---|---|
| channel | double | select image channels, the default is all channels except alpha. |
| fuzz | double | colors within this distance are considered equal |
| image | image-reference | the image reconstruction |
| metric | AE, MAE, MEPP, MSE, PAE, PSNR, RMSE | measure differences between images with this metric |
In this example, we compare the ImageMagick logo to a sharpened reconstruction:
use Image::Magick;
$logo=Image::Magick->New();
$logo->Read('logo:');
$sharp=Image::Magick->New();
$sharp->Read('logo:');
$sharp->Sharpen('0x1');
$difference=$logo->Compare(image=>$sharp, metric=>'rmse');
print $difference->Get('error'), "\n";
$difference->Display();
In addition to the reported root mean squared error of around 0.024, a difference image is displayed so you can visually identify the difference between the images.
Create an Image Montage
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,
$image->Montage(geometry=>'160x160', tile=>'2x2', texture=>'granite:');
And here is a list of Montage() parameters you can set:
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.
Working with Blobs
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.
| Method | Parameters | Return Value | Description |
|---|---|---|---|
| ImageToBlob | any image attribute | 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:
@blobs = $image->ImageToBlob();
open(DISPLAY,"| display -") || die;
binmode DISPLAY;
print DISPLAY $blobs[0];
close DISPLAY;
Method BlobToImage() returns an image or image sequence converted from the supplied blob:
@blob=$db->GetImage();
$image=Image::Magick->new(magick=>'jpg');
$image->BlobToImage(@blob);
Direct-access to Image Pixels
Use these methods to obtain direct access to the image pixels:
| Method | Parameters | Description |
|---|---|---|
| GetAuthenticPixels | geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer | return authentic pixels as a C pointer |
| GetVirtualPixels | geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer | return virtual pixels as a const C pointer |
| GetAuthenticIndexQueue | return colormap indexes or black pixels as a C pointer | |
| GetVirtualIndexQueue | return colormap indexes or black pixels as a const C pointer | |
| SyncAuthenticPixels | sync authentic pixels to pixel cache |
Miscellaneous Methods
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 Clone() method copies a set of images. For example,
$q = $p->Clone();
copies all the images from object $p to $q. You can use this method for single or multi-image sequences.
Coalesce() composites a set of images while respecting any page offsets and disposal methods. GIF, MIFF, and MNG animation sequences typically start with an image background and each subsequent image varies in size and offset. A new image sequence is returned with all images the same size as the first images virtual canvas and composited with the next image in the sequence.. For example,
$q = $p->Coalesce();
The ComplexImages() method performs complex mathematics on an image sequence. For example,
$p = $image->ComplexImages('conjugate');
The EvaluateImages() method applies an arithmetic, logical or relational expression to a set of images. For example,
$p = $image->EvaluateImages('mean');
averages all the images associated with object $image.
The Features() method returns features for each channel in the image in each of four directions (horizontal, vertical, left and right diagonals) for the specified distance. The features include the angular second momentum, contrast, correlation, sum of squares: variance, inverse difference moment, sum average, sum varience, sum entropy, entropy, difference variance, difference entropy, information measures of correlation 1, information measures of correlation 2, and maximum correlation coefficient. Values in RGB, CMYK, RGBA, or CMYKA order (depending on the image type).
@features = $image->Features(1);
The Flatten() method flattens a set of images and returns it. For example,
$p = $images->Flatten(background=>'none');
$p->Write('flatten.png');
The sequence of images is replaced by a single image created by composing each image after the first over the first image.
The Fx() method applies a mathematical expression to a set of images and returns the results. For example,
$p = $image->Fx(expression=>'(g+b)/2.0',channel=>'red');
$p->Write('fx.miff');
replaces the red channel with the average of the green and blue channels.
See FX, The Special Effects Image Operator for a detailed discussion of this method.
Histogram() returns the unique colors in the image and a count for each one. The returned values are an array of red, green, blue, opacity, and count values.
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:
$image->Crop('340x256+0+0');
$image->Mogrify('crop', '340x256+0+0');
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):
$image->MogrifyRegion('100x100+40+50', 'modulate', brightness=>50);
PerceptualHash() maps visually identical images to the same or similar hash-- useful in image retrieval, authentication, indexing, or copy detection as well as digital watermarking. For each channel and for the sRGB and the HCLp colorspaces, 7 hash values are returned For an sRGB images, for example, expect 42 perceptual hashes.
@phash = $image->PerceptualHash();
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:
($width, $height, $size, $format) = $image->Ping('logo.png');
($width, $height, $size, $format) = $image->Ping(file=>\*IMAGE);
($width, $height, $size, $format) = $image->Ping(blob=>$blob);
This a more efficient and less memory intensive way to query if an image exists and what its characteristics are.
Poly() builds a polynomial from the image sequence and the corresponding terms (coefficients and degree pairs):
$p = $image->Poly([0.5,1.0,0.25,2.0,1.0,1.0]);
PreviewImage() tiles 9 thumbnails of the specified image with an image processing operation applied at varying strengths. This may be helpful pin-pointing an appropriate parameter for a particular image processing operation. Choose from these operations: Rotate, Shear, Roll, Hue, Saturation, Brightness, Gamma, Spiff, Dull, Grayscale, Quantize, Despeckle, ReduceNoise, AddNoise, Sharpen, Blur, Threshold, EdgeDetect, Spread, Solarize, Shade, Raise, Segment, Swirl, Implode, Wave, OilPaint, CharcoalDrawing, JPEG. Here is an example:
$preview = $image->Preview('Gamma');
$preview->Display();
To have full control over text positioning you need font metric information. Use
($x_ppem, $y_ppem, $ascender, $descender, $width, $height, $max_advance) =
$image->QueryFontMetrics(parameters);
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
- bounds: x1
- bounds: y1
- bounds: x2
- bounds: y2
- origin: x
- origin: y
Use QueryMultilineFontMetrics() to get the maximum text width and height for multiple lines of text.
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.
@colors = $image->QueryColor();
($red, $green, $blue) = $image->QueryColor('cyan');
($red, $green, $blue, $alpha) = $image->QueryColor('#716baeff');
QueryColorname() accepts a color value and returns its respective name or hex value;
$name = $image->QueryColorname('rgba(80,60,0,0)');
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.
@fonts = $image->QueryFont();
$weight = ($image->QueryFont('Helvetica'))[5];
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.
@formats = $image->QueryFormat();
($adjoin, $blob_support, $raw, $decoder, $encoder, $description, $module) =
$image->QueryFormat('gif');
Call MagickToMime() with the image format name to get its MIME type such as image/tiff from tif.
$mime = $image->MagickToMime('tif');
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.
$image->RemoteCommand('image.jpg');
The Smush() method smushes a set of images together. For example,
$p = $image->Smush(stack=>{true,false},offset=>integer);
smushes together all the images associated with object $image. By default, images are smushed left-to-right. Set stack to True to smushed them top-to-bottom.
Statistics() returns the image statistics for each channel in the image. The returned values are an array of depth, minima, maxima, mean, standard deviation, kurtosis, skewness, and entropy values in RGB, CMYK, RGBA, or CMYKA order (depending on the image type).
@statistics = $image->Statistics();
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+0+0');
You can optionally add Image to any method name above. For example, PingImage() is an alias for method Ping().
Handling Exceptions
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 exceptions 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 (EvaluateSequence(), 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
Review the complete list of error and warning codes.
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);
Constants
PerlMagick includes these constants:
BlobError
BlobWarning
CacheError
CacheWarning
CoderError
CoderWarning
ConfigureError
ConfigureWarning
CorruptImageError
CorruptImageWarning
DelegateError
DelegateWarning
DrawError
DrawWarning
ErrorException
FatalErrorException
FileOpenError
FileOpenWarning
ImageError
ImageWarning
MissingDelegateError
MissingDelegateWarning
ModuleError
ModuleWarning
Opaque
OptionError
OptionWarning
QuantumDepth
QuantumRange
RegistryError
RegistryWarning
ResourceLimitError
ResourceLimitWarning
StreamError
StreamWarning
Success
Transparent
TypeError
TypeWarning
WarningException
XServerError
XServerWarning
You can access them like this:
Image::Magick->QuantumDepth