An object-oriented Python interface to ImageMagick is also available, see PythonMagick.
gunzip -c PerlMagick-1.32.tar.gz tar xvf PerlMagick-1.32.tar 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. libraries if they were included with your installed version of ImageMagick. Now type
perl Makefile.PL make make install
Use nmake instead of make on an NT system. For NT, you also need to copy IMagick.dll and X11.dll from the NT ImageMagick distribution to a path library such as c:\perl\lib.
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. You are now ready to utilize the PerlMagick methods from within your Perl scripts.
use Image::Magick;
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 catagories just mentioned. Review Miscellaneous Routines 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 $q;
To delete all the images but retain the Image::Magick object use
undef @$q;and finally, to delete a single image from a multi-image sequence, use
undef $q->[$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,
$ENV{PATH}='/bin:/usr/bin:/usr/local/bin';
#!/usr/local/bin/perl use Image::Magick; my($q, $x); $q = Image::Magick->new; $x = $q->Read('girl.gif', 'logo.gif', 'rose.gif'); warn "$x" if "$x"; $x = $q->Crop(geometry=>'100x100+100+100'); warn "$x" if "$x"; $x = $q->Write('x.gif'); 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:
#!/usr/local/bin/perl use Image::Magick; my($q, $r); $q = new Image::Magick; $q->Read('x1.gif'); $q->Read('j*.jpg'); $q->Read('k.miff[1,5,3]'); $q->Contrast; for ($x = 0; $q->[$x]; $x++) { $q->[$x]->Frame('100x200') if $q->[$x]->Get('magick') eq 'GIF'; undef $q->[$x] if $q->[$x]->Get('columns') < 100; } $r = $q->[1]; $r->Draw(pen=>'red', primitive=>'rectangle', points=>'20,20 100,100'); $s = $q->Montage; undef $q; $s->Write('x.miff');
Suppose you want to start out with a 100 by 100 pixel black canvas with a red pixel in the center. Try
$q = Image::Magick->new; $q->Set(size=>'100x100', 'pixel[50,50]'=>'255,0,0'); $q->ReadImage('xc:white');
Or suppose you want to convert your color image to grayscale:
$q->Quantize(colorspace=>'gray');
Other clever things you can do with 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 q undef @$p # delete the images but not the object p;
Routine | 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, each of these methods can take any parameter that SetAttribute knows about. For example,
$q->Write(filename=>'image.png', compress=>'None');
Use - as the filename to method Read to read from standard in or to method Write to write to standard out.
You can optionally add Image to any method name. For example, ReadImage is an alias for method Read.
$q->Crop(geometry=>'100x100+10+20'); $q->[$x]->Frame("100x200");
And here is a list of other image manipulation methods you can call:
Routine | Parameters | Description |
---|---|---|
AddNoise | noise=>{Uniform, Gaussian, Multiplicative, Impulse, Laplacian, Poisson} | add noise to an image |
Annotate | server=>string, font=>string, pointsize=>integer, box=>colorname, pen=>colorname, geometry=>geometry, text=>{string, @filename}, align=>{Left, Center, Right}, x=>integer, y=>integer | annotate an image with text |
Blur | factor=>percentage | blurs an image |
Border | geometry=>geometry, width=>integer, height=>integer, color=colorname | surround the image with a border of color |
Box | string | color for annotation bounding box |
Charcoal | factor=>percentage | simulate a charcoal drawing |
Chop | geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer | chop an image |
Composite | compose=>{Over, In, Out, Atop, Xor, Plus, Minus, Add, Subtract, Difference, Bumpmap, Replace, ReplaceRed, ReplaceGreen, ReplaceBlue, ReplaceMatte, Blend, Displace}, image=>image-handle, geometry=>geometry, x=>integer, y=>integer, gravity=>{NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast} | composite one image onto another |
Contrast | sharpen=>{True, False} | enhance or reduce the image contrast |
Clone | make a copy an image | |
Crop | geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer | crop an image |
Colorize | color=>colorname, pen=>colorname | colorize the image with the pen color |
Comment | string | add a comment to your image |
CycleColormap | amount=>integer | displace image colormap by amount |
Despeckle | reduce the speckles within an image | |
Draw | primitive={Point, Line, Rectangle, FillRectangle, Circle, FillCircle, Polygon, FillPolygon, Color, Matte, Text, Image, @filename}, points=>string, method={Point, Replace, Floodfill, Reset}, pen=>colorname, linewidth=>integer, server=>string, | annotate an image with one or more graphic primitives |
Edge | factor=>percentage | detect edges within an image |
Emboss | emboss the image | |
Enhance | apply a digital filter to enhance a noisy image | |
Equalize | perform histogram equalization to the image | |
Flip | create a mirror image by reflecting the image scanlines in the vertical direction | |
Flop | create a mirror image by reflecting the image scanlines in the horizontal direction | |
Frame | geometry=>geometry, width=>integer, height=>integer, inner=>integer, outer=>integer,color=>colorname | surround the image with an ornamental border |
Gamma | gamma=>double, red=>double, green=>double, blue=>double | gamma correct the image |
Implode | factor=>percentage | implode image pixels about the center |
Label | string | assign a label to an image |
Layer | layer={Red, Green, Blue, Matte} | extract a layer from the image |
Magnify | double the size of an image | |
Map | image=>image-handle, dither={True, False} | choose a particular set of colors from this image |
Minify | half the size of an image | |
Modulate | brightness=>double, saturation=>double, hue=>double | vary the brightness, saturation, and hue of an image |
Negate | gray=>{True, False} | apply color inversion to image |
Normalize | transform image to span the full range of color values | |
Magnify | double the size of an image | |
Map | image=>image-handle, dither={True, False} | choose a particular set of colors from this image |
Minify | half the size of an image | |
Modulate | brightness=>double, saturation=>double, hue=>double | vary the brightness, saturation, and hue of an image |
Negate | gray=>{True, False} | apply color inversion to image |
Normalize | transform image to span the full range of color values | |
OilPaint | radius=>integer | simulate an oil painting |
Opaque | color=>colorname, pen=>colorname | change this color to the pen color within the image |
pen | string | color for annotation text |
Quantize | colors=>integer, colorspace=>{RGB, Gray, Transparent, OHTA, XYZ, YCbCr, YCC, YIQ, YPbPr, YUV, CMYK}, treedepth=>integer, dither=>{True, False}, | preferred number of colors in the image |
Raise | geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer, raise=>{True, False} | lighten or darken image edges to create a 3-D effect |
ReduceNoise | add or reduce the noise in an image | |
Roll | geometry=>geometry, x=>integer, y=>integer | roll an image vertically or horizontally |
Rotate | degrees=>double, crop=>{True, False}, sharpen=>{True, False} | roll an image vertically or horizontally |
Sample | geometry=>geometry, width=>integer, height=>integer | scale image with pixel sampling |
Scale | geometry=>geometry, width=>integer, height=>integer | scale image to desired size |
Segment | colorspace=>{RGB, Gray, Transparent, OHTA, XYZ, YCbCr, YCC, YIQ, YPbPr, YUV, CMYK}, verbose={True, False}, cluster=>double, smooth=double | segment an image by analyzing the histograms of the color components and identifying units that are homogeneous |
Shade | geometry=>geometry, azimuth=>double, elevation=>double, color=>{true, false} | shade the image using a distant light source |
Sharpen | factor=>percentage | sharpen an image |
Shear | geometry=>geometry, x=>double, y=>double, crop=>{true, false} | shear the image along the X or Y axis by a positive or negative shear angle |
Signature | generate an MD5 signature for the image | |
Solarize | factor=>percentage | negate all pixels above the threshold level |
Spread | amount=>integer | displace image pixels by a random amount |
Swirl | degrees=>double | swirl image pixels about the center |
Texture | filename=>string | name of texture to tile onto the image background |
Transparent | color=>colorname | make this color transparent within the image |
Threshold | threshold=>integer | threshold the image |
Trim | remove edges that are the background color from the image | |
Wave | geometry=>geometry, amplitude=>double, wavelength=>double | alter an image along a sine wave |
Zoom | geometry=>geometry, width=>integer, height=>integer,
filter=>{Box, |
scale image to desired size |
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,
Draw(pen=>'red', primitive=>'rectangle', points=>'20,20 100,100 40,40 200,200 60,60 300,300');
Is eqivalent to
Draw(pen=>'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
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.
$q->Set(dither=>'True'); $q->[$x]->Set(delay=>3);
And here is a list of all the image attributes you can set:
Attribute | Values | Description |
---|---|---|
adjoin | {True, False} | join images into a single multi-image file |
background | string | image background color |
bordercolor | string | set the image border color |
colormap[i] | string | red, green, and blue color at position i |
colorspace | {RGB, Gray, Transparent, OHTA, XYZ, YCbCr, YCC, YIQ, YPbPr, YUV, CMYK} | type of colorspace |
colors | integer | preferred number of colors in the image |
compress | None, JPEG, LZW, Runlength, Zip | type of image compression |
density | geometry | vertical and horizontal resolution in pixels of the image |
dispose | {1, 2, 3, 4} | GIF disposal method |
delay | integer | this many 1/100ths of a second\fP must expire before displaying the next image in a sequence |
dither | {True, False} | apply Floyd/Steinberg error diffusion to the image |
display | string | specifies the X server to contact |
filename | string | set the image filename |
font | string | use this font when annotating the image with text |
format | string | set the image format |
iterations | integer | add Netscape loop extension to your GIF animation |
interlace | {None, Line, Plane, Partition} | the type of interlacing scheme |
loop | integer | add Netscape loop extension to your GIF animation |
magick | string | set the image format |
mattecolor | string | set the image matte color |
monochrome | {True, False} | transform the image to black and white |
page | string | preferred size and location of an image canvas |
pixel[x,y] | string | red, green, blue, and opacity value at (x,y) |
pointsize | integer | pointsize of the Postscript font |
preview_type | { 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, CharcoalDrawingPreview } | type of preview for the Preview image format |
quality | integer | JPEG/MIFF/PNG compression level |
scene | integer | image scene number |
subimage | integer | subimage of an image sequence |
subrange | integer | number of images relative to the base image |
server | string | specifies the X server to contact |
size | string | width and height of a raw image |
tile | string | tile name |
texture | string | name of texture to tile onto the image background |
treedepth | {0, 1, 2, 3, 4, 5, 6, 7, 8} | depth of the color classification tree |
undercolor | string | control undercolor removal and black generation on CMYK images |
verbose | {True, False} | print detailed information about the image |
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.
($a, $b, $c) = $q->Get('colorspace', 'magick', 'adjoin'); $width = $q->[3]->Get('columns');
In addition to all the attributes listed in Set an Image Attribute, you can get these additional attributes:
Attribute | Values | Description |
---|---|---|
base_columns | integer | base image width (before transformations) |
base_filename | string | base image filename (before transformations) |
base_rows | integer | base image height (before transformations) |
class | {Direct, Pseudo} | image class |
comment | string | image comment |
columns | integer | image width |
depth | integer | image depth |
directory | string | tile names from within an image montage |
filesize | integer | number of bytes of the image on disk |
gamma | double | gamma level of the image |
geometry | string | image geometry |
height | integer | the number of rows or height of an image |
label | string | image label |
matte | {True, False} | True if the image has transparency |
mean | double | the mean error per pixel computed when an image is color reduced |
montage | geometry | tile size and offset within an image montage |
normalized_max | double | the normalized max error per pixel computed when an image is color reduced |
normalized_mean | double | the normalized mean error per pixel computed when an image is color reduced |
packetsize | integer | the number of bytes in each pixel packet |
packets | integer | the number of runlength-encoded packets in the image |
rows | integer | the number of rows or height of an image |
signature | string | MD5 signature associated with the image |
text | string | any text associated with the image |
total_colors | integer | number of colors in the image |
type | {bilevel, greyscale, palette, true color, true color with transparency, color separation } | image type |
units | {Undefined, pixels / inch, pixels / centimeter} | units of resolution |
width | integer | the number of columns or width of an image |
x_resolution | integer | x resolution of the image |
y_resolution | integer | y resolution of the image |
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.
$q->Montage(geometry=>'160x160', tile=>'2x2', texture=>'granite:');
And here is a list of Montage parameters you can set:
Parameter | Values | Description |
---|---|---|
background | string | X11 color name |
borderwidth | integer | image border width |
compose | {Over, In, Out, Atop, Xor, Plus, Minus, Add, Subtract, Difference, Bumpmap, Replace, MatteReplace, Mask, Blend, Displace} | composite operator |
filename | string | name of montage image |
filter | {Box, |
use this filter to resize the image tile |
font | string | X11 font name |
foreground | string | X11 color name |
frame | geometry | surround the image with an ornamental border |
geometry | geometry | preferred tile and border size of each tile of the composite image |
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 |
pointsize | integer | pointsize of the Postscript font |
shadow | {True, False} | add a shadow beneath a tile to simulate depth |
texture | string | name of texture to tile onto the image background |
tile | geometry | number of tiles per row and column |
title | string | assign a title to the image montage |
transparent | string | make this color transparent within the image |
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.
$x = $q->Average();
averages all the images associated with object $q.
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:
$q->Crop('340x256+0+0'); $q->Mogrify('crop', '340x256+0+0');
Method MogrifyRegion applies a transform to a region of the image. It is similiar 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):
$q->MogrifyRegion('100x100+40+50', 'modulate', brightness=>50);
$p = $q->Clone();
copies all the images from object $q to $p.
Ping accepts one or more image file names and returns their respective width, height, size in bytes, and format (e.g. GIF, JPEG, etc.). For example,
($width, $height, $size, $format) = split(',', $q->Ping('logo.gif'));
This is a more efficient and less memory intensive way to query if an image exists and what its characteristics are. Note, only information about the first image in a multi-frame image file is returned.
You can optionally add Image to any method name above. For example, PingImage is an alias for method Ping.
Finally, for convenience, method QueryColor accepts one or more color names and returns their respective red, green, and blue color values:
($red, $green, $blue) = split(',', $q->QueryColor('cyan'));
$x = $q->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
$x = $q->Crop(...); warn "$x" if "$x"; # print the error message $x =~ /(\d+)/; print $1; # print the error number
$x = $q->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:
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 | XServerWarning | an X resource is unavailable |
310 | OptionWarning | a command-line option was malformed |
315 | PluginWarning | an ImageMagick plug-in returned a warning |
320 | MissingPluginWarning | the image type can not be read or written because the appropriate plug-in is missing |
325 | CorruptImageWarning | the image file may be corrupt |
330 | FileOpenWarning | the image file could not be opened |
400 | ResourceLimitError | a program resource is exhausted (e.g. not enough memory) |
405 | XServerError | an X resource is unavailable |
410 | OptionError | a command-line option was malformed |
The following illustrates how you can use a numeric status code:
$x = $q->Read('rose.gif'); $x =~ /(\d+)/; die "unable to continue" if ($1 == ResourceLimitError);