v7.1.2-34 Latest Stable Release

PerlMagick, Perl API

Use PerlMagick to read, manipulate, or write an image or image sequence from within a Perl script.

quickstart.sh
# Install via your favorite Package Manager
$ brew install imagemagick
# Convert PNG to WebP with compression
$ magick input.png -quality 85 output.webp
# Resize image maintaining aspect ratio
$ magick input.jpg -resize 800x600^ output.jpg

PerlMagick is an object-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-7.1.2-34
./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.

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 Taipei 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:

Read or Write Methods
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:

Image Manipulation Methods
Method Parameters Description
AdaptiveBlur geometry=>geometry, radius=>double, sigma=>double, bias=>double, channel=>channel_list adaptively blur the image with a Gaussian operator of the given radius and standard deviation (sigma). Decrease the effect near edges.
AdaptiveResize geometry=>geometry, width=>integer, height=>integer, filter=>filter_type, support=>double, blur=>double adaptively resize image using data dependant triangulation. Specify blur > 1 for blurry or < 1 for sharp
AdaptiveSharpen geometry=>geometry, radius=>double, sigma=>double, bias=>double, channel=>channel_list adaptively sharpen the image with a Gaussian operator of the given radius and standard deviation (sigma). Increase the effect near edges.
AdaptiveThreshold geometry=>geometry, width=>integer, height=>integer, bias=>double local adaptive thresholding.
AddNoise noise=>{Uniform, Gaussian, Multiplicative, Impulse, Laplacian, Poisson}, attenuate=>double, channel=>channel_list add noise to an image
AffineTransform affine=>array, translate=>float, float, scale=>float, float, rotate=>float, skewX=>float, skewY=>float, interpolate=>method, background=>color affine transform image
Affinity image=>image-handle, method=>{None, FloydSteinberg, Riemersma} choose a particular set of colors from this image
Annotate text=>string, font=>string, family=>string, style=>style, weight=>integer, pointsize=>integer, stroke=>color, fill=>color, undercolor=>color, kerning=>float, geometry=>geometry, gravity=>gravity, antialias=>boolean, x=>integer, y=>integer, align=>align annotate an image with text. See QueryFontMetrics to get font metrics without rendering any text.
AutoGamma channel=>channel_list automagically adjust gamma level of image
AutoLevel channel=>channel_list automagically adjust color levels of image
AutoOrient - adjusts an image so that its orientation is suitable for viewing (i.e. top-left orientation)
AutoThreshold method=>{Kapur, OTSU, Triangle} automatically perform image thresholding
Blur geometry=>geometry, radius=>double, sigma=>double, bias=>double, channel=>channel_list reduce image noise and reduce detail levels with a Gaussian operator of the given radius and standard deviation (sigma).
Border geometry=>geometry, width=>integer, height=>integer, bordercolor=>color, compose=>operator surround the image with a border of color
CannyEdge geometry=>geometry, radius=>double, sigma=>double, lower-percent=>double, upper-percent=>double use a multi-stage algorithm to detect a wide range of edges in the image.
Charcoal geometry=>geometry, radius=>double, sigma=>double simulate a charcoal drawing
Chop geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer, gravity=>gravity chop an image
CLAHE geometry=>geometry, width=>integer, height=>integer, number-bins=>integer, clip-limit=>double contrast limited adaptive histogram equalization.
Clamp channel=>channel_list set each pixel whose value is below zero to zero and any pixel above quantum range to quantum range.
Clip id=>name, inside=>boolean apply along a named path from the 8BIM profile.
ClipMask mask=>image-handle clip image as defined by the image mask
Clut image=>image-handle, interpolate=>method, channel=>channel_list apply a color lookup table to an image sequence
Color color=>color set the entire image to this color.
Colorize fill=>color, blend=>string colorize the image with the fill color
Colorspace colorspace=>{RGB, Gray, Transparent, OHTA, XYZ, YCbCr, YCC, YIQ, YPbPr, YUV, CMYK} set the image colorspace
Comment string add a comment to your image
Composite image=>image-handle, compose=>operator, mask=>image-handle, geometry=>geometry, x=>integer, y=>integer, gravity=>gravity composite one image onto another.
Contrast sharpen=>boolean enhance or reduce the image contrast
Convolve coefficients=>array, channel=>channel_list, bias=>double apply a convolution kernel to the image.
Crop geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer, fuzz=>double, gravity=>gravity crop an image
Deskew geometry=>string, threshold=>double straighten the image
Despeckle - reduce the speckles within an image
Distort points=>array, method=>{Affine, Perspective, Barrel, Resize, etc.}, virtual-pixel=>method distort image
Draw primitive=>{point, line, rectangle, circle, text, etc.}, points=>string, stroke=>color, fill=>color, font=>string annotate an image with one or more graphic primitives.
Edge radius=>double enhance edges within the image with a convolution filter.
Emboss geometry=>geometry, radius=>double, sigma=>double emboss the image with a convolution filter.
Equalize channel=>channel_list perform histogram equalization to the image
Extent geometry=>geometry, width=>integer, height=>integer, background=>color, gravity=>gravity set the image size and canvas extent
Flip - reflect the image scanlines in the vertical direction
Flop - reflect the image scanlines in the horizontal direction
GaussianBlur geometry=>geometry, radius=>double, sigma=>double reduce image noise and detail levels with a Gaussian operator.
Grayscale channel=>{Average, Brightness, Lightness, Rec601Luma, Rec709Luma, etc.} convert image to grayscale
Implode amount=>double implode image pixels about the center
Level levels=>string, gamma=>double, channel=>channel_list adjust the level of image contrast
LiquidResize geometry=>geometry, width=>integer, height=>integer, delta-x=>double, rigidity=>double rescale image with seam-carving.
Magnify - double the size of the image with pixel art scaling
MedianFilter geometry=>geometry, width=>integer, height=>integer replace each pixel with the median intensity pixel of a neighborhood.
Minify - half the size of an image
Modulate brightness=>double, saturation=>double, hue=>double vary the brightness, saturation, and hue of an image by percentage
Negate gray=>boolean, channel=>channel_list replace each pixel with its complementary color
Normalize channel=>channel_list transform image to span the full range of color values
OilPaint radius=>integer simulate an oil painting
Polaroid caption=>string, angle=>double, font=>string simulate a Polaroid picture.
Posterize levels=>integer, dither=>boolean reduce the image to a limited number of color levels
Quantize colors=>integer, colorspace=>colorspace, dither=>boolean preferred number of colors in the image
Resample density=>geometry, x=>double, y=>double resample image to desired resolution.
Resize geometry=>geometry, width=>integer, height=>integer, filter=>filter_type scale image to desired size.
Rotate degrees=>double, background=>color rotate an image
Sample geometry=>geometry, width=>integer, height=>integer scale image with pixel sampling.
Scale geometry=>geometry, width=>integer, height=>integer scale image to desired size
Sharpen geometry=>geometry, radius=>double, sigma=>double sharpen the image with a Gaussian operator.
Shave geometry=>geometry, width=>integer, height=>integer shave pixels from the image edges
Shear geometry=>geometry, x=>double, y=>double, fill=>color shear the image along the X or Y axis
Solarize threshold=>double negate all pixels above the threshold level
Spread radius=>double displace image pixels by a random amount
Strip - strip an image of all profiles and comments.
Swirl degrees=>double swirl image pixels about the center
Thumbnail geometry=>geometry, width=>integer, height=>integer changes image size and removes any associated profiles.
Threshold threshold=>string, channel=>channel_list threshold the image
Tint fill=>color, blend=>string tint the image with the fill color.
Transparent color=>color, invert=>boolean make this color transparent within the image
Trim - remove edges that are the background color from the image
UnsharpMask geometry=>geometry, radius=>double, sigma=>double, gain=>double, threshold=>double sharpen the image with the unsharp mask algorithm.
Vignette geometry=>geometry, radius=>double, sigma=>double, background=>color offset the edges of the image in vignette style
Wave geometry=>geometry, amplitude=>double, wavelength=>double alter an image along a sine wave
WhiteThreshold threshold=>string, channel=>channel_list force all pixels above the threshold intensity into white

Note that the geometry parameter is a shortcut for the width and height parameters (e.g. geometry=>'106x80' is equivalent to width=>106, height=>80).

You can optionally add Image to any method name above. For example, TrimImage() is an alias for method Trim().

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:

Image Attributes
Attribute Values Description
adjoin {True, False} join images into a single multi-image file
alpha {On, Off, Opaque, Transparent, Copy, Extract, Set} control of and special operations involving the alpha/matte channel
antialias {True, False} remove pixel aliasing
background color name image background color
bordercolor color name set the image border color
comment string set the image comment
compression {None, BZip, Fax, JPEG, JPEG2000, LZW, Zip} type of image compression
delay integer this many 1/100ths of a second must expire before displaying next image
density geometry vertical and horizontal resolution in pixels of the image
depth integer image depth
dither {True, False} apply error diffusion to the image
filename string set the image filename
fill color paint any areas inside the outline of drawn shape
font string use this font when annotating the image with text
fuzz integer colors within this distance are considered equal
gamma double gamma level of the image
gravity {NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast} type of image gravity
interlace {None, Line, Plane, Partition, JPEG, GIF, PNG} the type of interlacing scheme
loop / iterations integer add Netscape loop extension to your GIF animation
magick string set the image format
matte {True, False} enable the image matte channel
pointsize integer pointsize of the Postscript or TrueType font
quality integer JPEG/MIFF/PNG compression level
scene integer image scene number
size string width and height of a raw image
stroke color paint along the outline of a shape
type {Bilevel, Grayscale, Palette, TrueColor, ColorSeparation} image type
verbose {True, False} print detailed information about the image

SetAttribute() is an alias for method Set().

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:

Image Attributes (Read-Only/Get)
Attribute Values Description
base-columns integer base image width (before transformations)
base-rows integer base image height (before transformations)
class {Direct, Pseudo} image class
colors integer number of unique colors in the image
columns integer image width
copyright string get PerlMagick's copyright
elapsed-time double elapsed time in seconds since the image was created
error double the mean error per pixel computed with methods Compare() or Quantize()
filesize integer number of bytes of the image on disk
format string get the descriptive image format
height integer the number of rows or height of an image
signature string SHA-256 message digest associated with the image pixel stream
taint {True, False} True if the image has been modified
version string get PerlMagick's version
width integer the number of columns or width of an image

GetAttribute() is an alias for method Get().

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:

Compare 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:

Montage Parameters
Parameter Values Description
background color name background color name
border integer image border width
filename string name of montage image
fill color name fill color for annotations
font string X11 font name
frame geometry surround the image with an ornamental border
geometry geometry preferred tile and border size of each tile
gravity NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast direction image gravitates to within a tile
label string assign a label to an image
mode Frame, Unframe, Concatenate thumbnail framing options
shadow {True, False} add a shadow beneath a tile to simulate depth
tile geometry the number of tiles per row and page (e.g. 6x4)
title string assign a title to the image montage

MontageImage() is an alias for method Montage().

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.

Blob Methods
Method Parameters Return Value Description
ImageToBlob any image attribute an array of image data convert an image or image sequence to an array of blobs
BlobToImage one or more blobs the number of blobs converted 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:

Direct-access to 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
SyncAuthenticPixels - sync authentic pixels to pixel cache

Miscellaneous Methods

The Append() method appends 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.

Coalesce() composites a set of images while respecting any page offsets and disposal methods.

$q = $p->Coalesce();

Method Mogrify() is a single entry point for the image manipulation methods. For example, these calls are equivalent:

$image->Crop('340x256+0+0');
$image->Mogrify('crop', '340x256+0+0');

Ping() is a convenience method that returns information about an image without having to read the image into memory:

($width, $height, $size, $format) = $image->Ping('logo.png');

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. A numeric code greater or equal to 400 is an error and indicates the operation failed completely.

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

Review the complete list of error and warning codes.

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