Perl Magick

Contents


Introduction

PerlMagick, version 1.12, 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 3.8.7 or above and Perl version 5.002 or greater installed on your system.

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.12.tar.gz
    tar xvf PerlMagick-1.12.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 functions 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 functions.

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 functions. 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 functions to manipulate an image sequence.

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,3,5]');
    $q->Contrast;
    for ($x = 0; $q->[$x]; $x++)
    {
      if ($q->[$x]->Get('magick') eq 'GIF')
        $q->[$x]->Frame('100x200');
      if ($q->[$x]->Get('columns') < 100)
        undef $q->[$x];
    }
    $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 functions 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 or a list of any warnings read an image or image sequence
Write filename the number of images written or a list of any warnings write an image or image sequence
Display server name the number of images displayed or a list of any warnings display the image or image sequence to an X server
Animate server name the number of images animated or a list of any warnings animate image sequence to an X server

For convenience, each of these routines can take any parameter that SetAttribute knows about. For example,

    $x->write(filename=>'image.png', compress=>'False');

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

Back to Contents


Manipulate an Image

Once you create an image with, for example, function 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 function:

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

And here is a list of other image manipulation functions 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,x=>integer, y=>integer 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, treedepth=>integer, dither=>{True, False}, colorspace=>{RGB, Gray, Transparent, OHTA, XYZ, YCbCr, YCC, YIQ, YPbPr, YUV} 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}, 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 function 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} type of colorspace
colors integer preferred number of colors in the image
compress No, Runlength, Zip type of image compression
density geometry vertical and horizontal resolution in pixels of the image
dispose geometry 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`h 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 the Postscript page
pixel[x,y] string red, green, blue, and opacity value at (x,y)
pointsize integer pointsize of the Postscript font
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 function 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 function 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(gometry=>'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
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
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 function 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 function followed by any parameters the function 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.

You can optionally add Image to any routine name. For example, CloneImage is an alias for function Clone.

Back to Contents


Home Page Image manipulation software that works like magic.