Perl Magick;NF,
DPerl Magick




Contents







Introduction

O
PerlMagick,Jversion 1.29, is an objected-oriented MPerl interface to ImageMagick. Use the?module to read, manipulate, or write an image or image sequenceLfrom within a Perl script. This makes it very suitable for Web CGI scripts.One example is?MogrifyMagick a PerlFscript*that utilitizes PerlMagick to allowNWeb based image manipulation and conversion. You must have ImageMagickM3.9.3 or above and Perl version 5.002 or greater installed on your system for"either of these utilities to work.

LAn object-oriented Python interface to ImageMagick is also available,Osee PythonMagick.



*Back to Contents






Installation

H
Get the 3PerlMagick distribution and type the following:



$    gunzip -c PerlMagick-1.29.tar.gz    tar xvf PerlMagick-1.29.tar    cd PerlMagick


FNext, edit Makefile.PL and change LIBS and INC to include theHappropriate path information to the required libMagick library.HYou will also need paths to JPEG, PNG, TIFF, etc. libraries if they wereEincluded with your installed version of ImageMagick. Now type



    perl Makefile.PL    make    make install


JYou typically need to be root to install the software. There areKways around this. Consult the Perl manual pages for more information. YouGare now ready to utilize the PerlMagick methods from within your Perl scripts.



*Back to Contents






Overview

E
Any script that wants to use PerlMagick methods must first7define the methods within its namespace. Do this with:



    use Image::Magick;


ENext you will want to read an image or image sequence, manipulate it,?and then display or write it. The input and output methods forLPerlMagick are defined in Read or Write an Image.JSee Set an Image Attribute for methods that affect the*way an image is read or written. Refer toJManipulate an Image for a list of methods to transformFan image. Get an Image Attribute describes how to-retrieve an attribute for an image. Refer toECreate an Image Montage for details about tiling Hyour images as thumbnails on a background. Finally, some methods do not=neatly fit into any of the catagories just mentioned. ReviewGMiscellaneous Routines for a list of these methods.

IOnce you are finished with a PerlMagick object you should considerLdestroying it. Each image in an image sequence is stored in virtual memory.GThis can potentially add up to mega-bytes of memory. Upon destroying aFPerlMagick object, the memory is returned for use by other PerlJmethods. The recommended way to destroy an object is with undef:




    undef $q;


ITo delete all the images but retain the Image::Magick object use



    undef @$q;
Fand finally, to delete a single image from a multi-image sequence, use



    undef $q->[$x];


IThe next section illustrates how to use various PerlMagick methods to manipulate an image sequence.

GSome of the PerlMagick methods require external programs such as@Ghostscript. This may require an explicit path in your9PATH environment variable to work properly. For example,



.    $ENV{PATH}='/bin:/usr/bin:/usr/local/bin';



*Back to Contents





Example Script

1
Here is an example script to get you started:



    #!/usr/local/bin/perl    use Image::Magick;    my($q, $x);    $q = Image::Magick->new;6    $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";


IThe script reads three images, crops them, and writes a single image as aHGIF animation sequence. In many cases you may want to access individualEimages 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++)    {E      $q->[$x]->Frame('100x200') if $q->[$x]->Get('magick') eq 'GIF';7      undef $q->[$x] if $q->[$x]->Get('columns') < 100;    }    $r = $q->[1];J    $r->Draw(pen=>'red', primitive=>'rectangle', points=>'20,20 100,100');    $s = $q->Montage;
    undef $q;    $s->Write('x.miff');


GSuppose you want to start out with a 100 by 100 pixel black canvas witha red pixel in the center. Try



    $q = Image::Magick->new;8    $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');


EOther clever things you can do with PerlMagick objects include



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

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

     % *   ( +   * =   ) 0 
Read or Write Methods
RoutineParametersReturn ValueDescription
Read one or more filenamesthe number of images read read an image or image sequence
Writefilenamethe number of images written write an image or image sequence
Displayserver namethe number of images displayed display the image or image sequence to an X server
Animateserver namethe number of images animated animate image sequence to an X server


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



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


CUse - as the filename to method Read to read fromAstandard in or to method Write to write to standard out.

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



*Back to Contents






Manipulate an Image

M
Once you create an image with, for example, method ReadImage youKmay want to operate on it. Below is a list of all the image manipulations <methods 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");


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

    D   &  $   O 4   ,  $ &  O   / +  ! /    O   9 0   &  ! ,  .   @  $ '    :  6  M  M  O 7  E "  $ 0   %  &  ; <  $  < ?   )  A  ! #  9 >   $  N 2  O ?  .  J 3  N 3  7 *  7 &  M N  8 7  $   D K  2  $ 6  ! 3  ! .  " <  " 7  $   D  : +  O & 
Image Manipulation Routines
RoutineParametersDescription
AddNoisenoise=>{Uniform, Gaussian, Multiplicative, Impulse, Laplacian, Poisson} add noise to an image
AnnotateJ server=>string, font=>string, pointsize=>integer,L box=>colorname, pen=>colorname, geometry=>geometry,J text=>{string, @filename}, align=>{Left, Center, Right},( x=>integer, y=>integer annotate an image with text
Blurfactor=>percentageblurs an image
Bordergeometry=>geometry, width=>integer, height=>integer, color=colornamesurround the image with a border of color
Boxstringcolor for annotation bounding box
Charcoalfactor=>percentagesimulate a charcoal drawing
Chopgeometry=>geometry, width=>integer, height=>integer,- x=>integer, y=>integerchop an image
Compositecompose=>{Over, In, Out, Atop, Xor, Plus,K Minus, Add, Subtract, Difference, Bumpmap, Replace, MatteReplace, Mask,K Blend, Displace}, image=>image-handle, geometry=>geometry,E x=>integer, y=>integer, gravity=>{NorthWest, North,D NorthEast, West, Center, East, SouthWest, South, SouthEast}composite one image onto another
Contrastsharpen=>{True, False}enhance or reduce the image contrast
Clonemake a copy an image
Cropgeometry=>geometry, width=>integer, height=>integer,- x=>integer, y=>integercrop an image
Colorizecolor=>colorname, pen=>colornamecolorize the image with the pen color
Commentstringadd a comment to your image
CycleColormapamount=>integerdisplace image colormap by amount
Despecklereduce the speckles within an image
DrawI primitive={Point, Line, Rectangle, FillRectangle, Circle, FillCircle,I Polygon, FillPolygon, Color, Matte, Text, Image, @filename},L points=>string, method={Point, Replace, Floodfill, Reset},L pen=>colorname, linewidth=>integer, server=>string, annotate an image with one or more graphic primitives
Edgefactor=>percentagedetect edges within an image
Embossemboss the image
Enhanceapply a digital filter to enhance a noisy image
Equalizeperform histogram equalization to the image
Flipcreate a mirror image by reflecting the image scanlines in the vertical direction
Flopcreate a mirror image by reflecting the image scanlines in the horizontal direction
Framegeometry=>geometry, width=>integer, height=>integer,M inner=>integer, outer=>integer,color=>colornamesurround the image with an ornamental border
Gammagamma=>double, red=>double, green=>double, blue=>doublegamma correct the image
Implodefactor=>percentageimplode image pixels about the center
Labelstringassign a label to an image
Magnifydouble the size of an image
Mapimage=>image-handle, dither={True, False}choose a particular set of colors from this image
Minifyhalf the size of an image
Modulatebrightness=>double, saturation=>double, hue=>doublevary the brightness, saturation, and hue of an image
Negategray=>{True, False}apply color inversion to image
Normalizetransform image to span the full range of color values
OilPaintradius=>integersimulate an oil painting
Opaquecolor=>colorname, pen=>colornamechange this color to the pen color within the image
penstringcolor for annotation text
Quantize colors=>integer, colorspace=>{RGB, Gray, Transparent, OHTA, XYZ,D YCbCr, YCC, YIQ, YPbPr, YUV, CMYK}, treedepth=>integer," dither=>{True, False}, preferred number of colors in the image
Raisegeometry=>geometry, width=>integer, height=>integer,C x=>integer, y=>integer, raise=>{True, False}lighten or darken image edges to create a 3-D effect
ReduceNoiseadd or reduce the noise in an image
Rollgeometry=>geometry, x=>integer, y=>integerroll an image vertically or horizontally
Rotatedegrees=>double, crop=>{True, False}, sharpen=>{True, False}roll an image vertically or horizontally
Samplegeometry=>geometry, width=>integer," height=>integer scale image with pixel sampling
Scalegeometry=>geometry, width=>integer," height=>integer scale image to desired size
Segmentcolorspace=>{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
Shadegeometry=>geometry, azimuth=>double,: elevation=>double, color=>{true, false} shade the image using a distant light source
Sharpenfactor=>percentagesharpen an image
Sheargeometry=>geometry, x=>double, y=>double, crop=>{true, false}shear the image along the X or Y axis by a positive or negative shear angle
Signaturegenerate an MD5 signature for the image
Solarizefactor=>percentagenegate all pixels above the threshold level
Spreadamount=>integerdisplace image pixels by a random amount
Swirldegrees=>doubleswirl image pixels about the center
Texturefilename=>stringname of texture to tile onto the image background
Transparentcolor=>colornamemake this color transparent within the image
Thresholdthreshold=>integerthreshold the image
Trimremove edges that are the background color from the image
Wavegeometry=>geometry, amplitude=>double,% wavelength=>double alter an image along a sine wave
Zoomgeometry=>geometry, width=>integer, height=>integer,5 filter=>{Box, Mitchell, Triangle}scale image to desired size


ANote, that the geometry parameter is a short cut for theOwidth and height parameters (e.g. geometry=>'106x80'2is equivalent to width=>106, height=>80).

OYou can specify @filename in both Annotate and Draw.JThis 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


GYou can optionally add Image to any method name. For example,8TrimImage is an alias for method Trim.

5Most of the attributes listed above have an analog in>convert. See the documentation for0a more detailed description of these attributes.



*Back to Contents






Set an Image Attribute

D
Use method 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:

     5   !   %   :  Q    2  * $   D      N   =   ,   !   <      <  ) )   <      $   1   9 #  E   +  G 7         (   6   ,   *      <  , 2   I   5 
Image Attributes
AttributeValuesDescription
adjoin{True, False}join images into a single multi-image file
backgroundstringimage background color
bordercolorstringset the image border color
colormap[i]stringred, green, and blue color at position i
colorspace{RGB, Gray, Transparent, OHTA, XYZ, YCbCr, YCC, YIQ, YPbPr, YUV, CMYK}type of colorspace
colorsintegerpreferred number of colors in the image
compressNone, JPEG, LZW, Runlength, Ziptype of image compression
densitygeometryvertical and horizontal resolution in pixels of the image
dispose{1, 2, 3, 4}GIF disposal method
delayintegerthis 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
displaystringspecifies the X server to contact
filenamestringset the image filename
fontstringuse this font when annotating the image with text
formatstringset the image format
iterationsintegeradd Netscape loop extension to your GIF animation
interlace{None, Line, Plane, Partition}the type of interlacing scheme
loopintegeradd Netscape loop extension to your GIF animation
magickstringset the image format
mattecolorstringset the image matte color
monochrome{True, False}transform the image to black and white
pagestringpreferred size and location of an image canvas
pixel[x,y]stringred, green, blue, and opacity value at (x,y)
pointsizeintegerpointsize of the Postscript font
preview_type{ Rotate, Shear, Roll, Hue, Saturation, Brightness, Gamma, Spiff,O Dull, Grayscale, Quantize, Despeckle, ReduceNoise, AddNoise, Sharpen, Blur,J Threshold, EdgeDetect, Spread, Solarize, Shade, Raise, Segment, Swirl,; Implode, Wave, OilPaint, CharcoalDrawingPreview } type of preview for the Preview image format
qualityintegerJPEG quality setting
sceneintegerimage scene number
subimageintegersubimage of an image sequence
subrangeintegernumber of images relative to the base image
serverstringspecifies the X server to contact
sizestringwidth and height of a raw image
tilestringtile name
texturestringname of texture to tile onto the image background
treedepth{0, 1, 2, 3, 4, 5, 6, 7, 8} depth of the color classification tree
undercolorstringcontrol undercolor removal and black generation on CMYK images
verbose{True, False}print detailed information about the image


ANote, that the geometry parameter is a short cut for theOwidth and height parameters (e.g. geometry=>'106x80'2is equivalent to width=>106, height=>80).

:SetAttribute is an alias for method Set.

5Most of the attributes listed above have an analog in>convert. See the documentation for0a more detailed description of these attributes.



#Back to Contents






Get an Image Attribute

D
Use method Get to get an image attribute. For example,



=    ($a, $b, $c) = $q->Get('colorspace', 'magick', 'adjoin');%    $width = $q->[3]->Get('columns');


HIn addition to all the attributes listed in Set an Image7Attribute, you can get these additional attributes:

     4   7   5               2   /   #      3      -   K   7   U   V   3   ?   3   2   -   (  M   :    5   $   $ 
Image Attributes
AttributeValuesDescription
base_columnsintegerbase image width (before transformations)
base_filenamestringbase image filename (before transformations)
base_rowsintegerbase image height (before transformations)
class{Direct, Pseudo}image class
commentstringimage comment
columnsintegerimage width
depthintegerimage depth
directorystringtile names from within an image montage
filesizeintegernumber of bytes of the image on disk
gammadoublegamma level of the image
geometrystringimage geometry
heightintegerthe number of rows or height of an image
labelstringimage label
matte{True, False}True if the image has transparency
meandoublethe mean error per pixel computed when an image is color reduced
montagegeometrytile size and offset within an image montage
normalized_maxdoublethe normalized max error per pixel computed when an image is color reduced
normalized_meandoublethe normalized mean error per pixel computed when an image is color reduced
packetsizeintegerthe number of bytes in each pixel packet
packetsintegerthe number of runlength-encoded packets in the image
rowsintegerthe number of rows or height of an image
signaturestringMD5 signature associated with the image
textstringany text associated with the image
total_colorsintegernumber 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
widthintegerthe number of columns or width of an image
x_resolutionintegerx resolution of the image
y_resolutionintegery resolution of the image


:GetAttribute is an alias for method Get.

5Most of the attributes listed above have an analog in>convert. See the documentation for0a more detailed description of these attributes.



#Back to Contents






Create an Image Montage

H
Use method Montage to create a composite image by combiningNseveral separate images. The images are tiled on the composite image with theFname of the image optionally appearing just below the individual tile. For example,



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


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

          2     - 3         7   M  ) 6   %  ( $   +   8   <   -   .   7 
Montage Parameters
ParameterValuesDescription
backgroundstringX11 color name
borderwidthintegerimage border width
compose{Over, In, Out, Atop, Xor, Plus, Minus, Add,F Subtract, Difference, Bumpmap, Replace, MatteReplace, Mask, Blend, Displace}composite operator
filenamestring name of montage image
filter{Box, Mitchell, Triangle}use this filter to resize the image tile
fontstringX11 font name
foregroundstringX11 color name
framegeometrysurround the image with an ornamental border
geometrygeometrypreferred tile and border size of each tile of the composite image
gravity{NorthWest, North, NorthEast, West,5 Center, East, SouthWest, South, SouthEast}direction image gravitates to within a tile
labelstringassign a label to an image
mode{Frame, Unframe, Concatenate}thumbnail framing options
pointsizeintegerpointsize of the Postscript font
shadow{True, False}add a shadow beneath a tile to simulate depth
texturestringname of texture to tile onto the image background
tilegeometrynumber of tiles per row and column
titlestringassign a title to the image montage
transparentstringmake this color transparent within the image


ANote, that the geometry parameter is a short cut for theOwidth and height parameters (e.g. geometry=>'106x80'2is equivalent to width=>106, height=>80).

>MontageImage is an alias for method Montage.

5Most of the attributes listed above have an analog in>montage. See the documentation for0a more detailed description of these attributes.








%Miscellaneous Routines


G
The Average method averages a set of images. For example,



    $x = $q->Average();


;averages all the images associated with object $q.

=Method Mogrify is a single entry point for the imageDmanipulation methods (Manipulate an Image). TheBparameters 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');


DMethod MogrifyRegion applies a transform to a region of theEimage. It is similiar to Mogrify but begins with the regionEgeometry. For example, suppose you want to brighten a 100x100 region"of your image at location (40,50):



C    $q->MogrifyRegion('100x100+40+50', 'modulate', brightness=>50);




C

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



    $p = $q->Clone();


=copies all the images from object $q to $p.

DPing accepts one or more image file names and returns theirLrespective width, height, size in bytes, and format (e.g. GIF, JPEG, etc.). For example,



I    ($width, $height, $size, $format) = split(',', $q->Ping('logo.gif'));


KThis is a more efficient and less memory intensive way to query if an imageJexists and what its characteristics are. Note, only information about the4first image in a multi-frame image file is returned.

MYou can optionally add Image to any method name above. For example,8PingImage is an alias for method Ping.

HFinally, for convenience, method QueryColor accepts one or moreKcolor names and returns their respective red, green, and blue color values:



?    ($red, $green, $blue) = split(',', $q->QueryColor('cyan'));

#Back to Contents



Handling Errors


I
All PerlMagick methods return an undefined string context uponGsuccess. If any problems occur, the error is returned as a string withBan embedded numeric status code. A status code less than 400 is aLwarning. This means that the operation did not complete but was recoverableGto some degree. A numeric code greater or equal to 400 is an error andNindicates the operation failed completely. Here is how errors are returned forthe different methods:



    H
  • Routines which return a number (e.g. Read, Write):
        $x = $q->Read(...);5    warn "$x" if "$x";      # print the error message    $x =~ /(\d+)/;5    print $1;               # print the error number =    print 0+$x;             # print the number of images read
    K
  • Routines which operate on an image (e.g. Zoom, Crop):
        $x = $q->Crop(...);5    warn "$x" if "$x";      # print the error message    $x =~ /(\d+)/;5    print $1;               # print the error number 
    E
  • Routines which return images (Average, Montage,6Clone) should be checked for errors this way:

    

        $x = $q->Montage(...);5    warn "$x" if !ref($x);  # print the error message    $x =~ /(\d+)/;5    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:

    7   C   '   .   4   H   (   -   C   '   . 
Error and Warning Codes
CodeMnemonicDescription
0Successmethod completed without an error or warning
300ResourceLimitWarninga program resource is exhausted (e.g. not enough memory)
305XServerWarningan X resource is unavailable
310OptionWarninga command-line option was malformed
315PluginWarningan ImageMagick plug-in returned a warning
320MissingPluginWarningthe image type can not be read or written because the appropriate  plug-in is missing
325CorruptImageWarningthe image file may be corrupt
330FileOpenWarningthe image file could not be opened
400ResourceLimitErrora program resource is exhausted (e.g. not enough memory)
405XServerErroran X resource is unavailable
410OptionErrora 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


2Home PageIImage manipulation software that works like magic.