Perl Magick

Contents


Introduction

PerlMagick, version 1.24, 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. One example is MogrifyMagick a Perl script that utilitizes PerlMagick to allow Web based image manipulation and conversion. You must have ImageMagick 3.9.2 or above and Perl version 5.002 or greater installed on your system for either of these utilities to work.

An object-oriented Python interface to ImageMagick is also available, see PythonMagick.

Back to Contents


Installation

Get the PerlMagick distribution and type the following:

    gunzip -c PerlMagick-1.24.tar.gz
    tar xvf PerlMagick-1.24.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

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 routines from within your Perl scripts.

Back to Contents


Overview

Any script that wants to use PerlMagick routines must first define the routines within its namespace. Do this with:

    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 routines for PerlMagick are defined in Read or Write an Image. See Set an Image Attribute for routines 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 routines 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';

Back to Contents


Example Script

Here is an example script to get you started:

    #!/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->Set(colorspace=>'gray');
    $q->Quantize();

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;

Back to Contents


Read or Write an Image

Use the methods listed below to either read, write, or display an image or image sequence.

Read or Write Functions
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 routines can take any parameter that SetAttribute knows about. For example,

    $q->write(filename=>'image.png', compress=>'None');

You can optionally add Image to any routine name. For example, ReadImage is an alias for method Read.

Back to Contents


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 routines available to you with PerlMagick. Here is an example call to an image manipulation method:

    $q->Crop(geometry=>'100x100+10+20');
    $q->[$x]->Frame("100x200");

And here is a list of other image manipulation methods you can call:

Image Manipulation Routines
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
Border geometry=>geometry, width=>integer, height=>integer, color=colorname surround the image with a border of color
Blur factor=>percentage blurs an image
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, MatteReplace, Mask, 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 annotate an image with a comment
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
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
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, Mitchell, Triangle} 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 routine 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.

Back to Contents


Set an Image Attribute

Use routine Set to set an image attribute. For example,

    $q->Set(dither=>'True');
    $q->[$x]->Set(delay=>3);

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
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 regulate the animation of a sequence of GIF images within Netscape
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
number integer preferred number of colors in the image
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 quality setting
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.

Back to Contents


Get an Image Attribute

Use routine Get to get an image attribute. For example,

    ($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:

Image 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 {DirectClass, PseudoClass} image class
comment string image comment
columns integer image width
depth integer image depth
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
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
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.

Back to Contents


Create an Image Montage

Use routine 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,

    $q->Montage(geometry=>'160x160', tile=>'2x2', texture=>'granite:');

And here is a list of Montage parameters you can set:

Montage Parameters
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, Mitchell, Triangle} 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 string 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.


Miscellaneous Routines

The Average routine averages a set of images. For example,

    $x = $q->Average();

averages all the images associated with object $q.

Function Mogrify is a single entry point for the image manipulation routines (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');

The Clone routine copies a set of images. For example,

    $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 routine name above. For example, PingImage is an alias for method Ping.

Finally, for convenience, routine QueryColor accepts one or more color names and returns their respective red, green, and blue color values:

    ($red, $green, $blue) = $QueryColor('red', 'white', 'blue');
Back to Contents

Handling Errors

All PerlMagick routines 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:

  • Routines which return a number (e.g. Read, Write):
        $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
    
  • Routines which operate on an image (e.g. Zoom, Crop):
        $x = $q->Crop(...);
        warn "$x" if "$x";      # print the error message
        $x =~ /(\d+)/;
        print $1;               # print the error number 
    
  • Routines which return images (Average, Montage, Clone) should be checked for errors this way:

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

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);
Back to Contents


Home Page Image manipulation software that works like magic.