Perl Magick9NG,
DPerl Magick




Contents







Introduction

H
PerlMagick, Jversion 4.18, 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.IYou must have ImageMagick 4.2.1 or above and Perl version 5.002 orMgreater installed on your system for either of these utilities to work. PerlNversion 5.005_02 or greater is required for PerlMagick to work on an NTsystem.

GThere are a number of useful scripts available to show you the value ofOPerlMagick. You can do Web based image manipulation and conversion withMMogrifyMagick, or useDL-systems toBcreate images of plants using mathematical constructs, and finallyEnavigate through collections of thumbnail images and select the imageto view with theRWebMagick Image Navigator.

=You can try PerlMagick from your Web browser at the (ImageMagick Studio. Or, you can seeIexamples of select PerlMagick functions.

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



*Back to Contents






Installation


UNIX

DImageMagick must already be installed on your system. Next, get theBPerlMagick*distribution and unpack it as shown below:



1    gunzip -c PerlMagick-4.18.tar.gz | tar -xvf -    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. delegates if they wereFincluded with your installed version of ImageMagick. Build andinstall it like this:



    perl Makefile.PL    make    make install


IFor Unix, you typically need to be root to install the software.CThere are ways around this. Consult the Perl manual pages for moreinformation. 

+Windows NT / Windows 95

LImageMagick must already be installed on your system. Also, the ImageMagicksource distribution forKWindows NT is required.LYou must also have the nmake from the Visual C++ or J++ developmentIenvironment. Copy \bin\IMagick.dll and \bin\X11.dll toLa directory in your dynamic load path such as c:\perl\site\5.00502. Next, type



    cd PerlMagick     copy Makefile.nt Makefile.PL    perl Makefile.PL	    nmake    nmake install


0Running the Regression Tests

&To verify a correct installation, type




    make test


&Use nmake test under Windows.HThere are ao few demonstration scripts available to exercise many of the.functions PerlMagick can perform. Type



    cd demo    make


?You are now ready to utilize the PerlMagick methods fromwithin your Perl scripts.



*Back to Contents






Overview

E
Any script that wants to use PerlMagick methods must firstHdefine the methods within its namespace and instantiate an image object. Do this with:



    use Image::Magick;    $image=Image::Magick->new;


5The new method takes the same parameters as /SetAttribute. For example,



/    $image=Image::Magick->new(size=>'384x256');


FNext 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. ReviewFMiscellaneous Methods 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 $image;


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



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



    undef $image->[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 your:PATH 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($image, $x);#    $image = Image::Magick->new;=    $x = $image->Read('girl.gif', 'logo.gif', 'rose.gif');    warn "$x" if "$x";9    $x = $image->Crop(geometry=>'100x100+100+100');    warn "$x" if "$x";#    $x = $image->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($image, $p, $q);    $image = new Image::Magick;    $image->Read('x1.gif');    $image->Read('j*.jpg');'    $image->Read('k.miff[1, 5, 3]');    $image->Contrast;&    for ($x = 0; $image->[x]; $x++)    {W      $image->[x]->Frame('100x200') if $image->[x]->Get('magick') eq 'GIF';I      undef $image->[x] if $image->[x]->Get('columns') < 100;    }    $p = $image->[1];U    $p->Draw(pen=>'red', primitive=>'rectangle', points=>20,20 100,100');    $q = $p->Montage();    undef $image;    $q->Write('x.miff');


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



#    $image = Image::Magick->new;'    $image->Set(size=>'100x100');%    $image->ReadImage('xc:white');-    $image->Set('pixel[49,49]'=>'red');


=Or suppose you want to convert your color image to grayscale:



/    $image->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 pB    push(@$q, @$p);  # push the images from object p onto object 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. 

     % *   ( +  @ H   * =   ) 0 
Read or Write Methods
MethodParametersReturn 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
Bloban array of image data in the respective image formatconvert an image or image sequence to an array of binary data
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


IFor convenience, methods Write, Blob, Display,0and Animate can take any parameter that<SetAttribute knows about. For example, 



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



    binmode STDOUT;    $image->Write('gif:-');
?To read an image in the GIF format from a PERL filehandle, use:



5    $image = Image::Magick->new(magick=>'GIF');    open(DATA, 'image.gif');#    $image->Read(file=>DATA);    close(DATA);
>To write an image in the PNG format to a PERL filehandle, use:



    $filename = "image.png";     open(DATA, ">$filename");<    $image->Write(file=>DATA, filename=>$filename);    close(DATA);


JBlob returns the image data in their respective formats. You canJthen print it, save it to an ODBC database, write it to a file, or pipe itto a display program:



    @blobs = $image->Blob();'    open(DISPLAY,"| display -") || die;    binmode DISPLAY;    print DISPLAY $blobs[0];    close DISPLAY;




HYou 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. There are Mexamples of selectPerlMagick methods.8Here is an example call to an image manipulation method:



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


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

    H   '  '   Y 4  ' &  Y     %  P H  ? 0   &  3 +  ?  $ /  Y   $ ,  .   @  ' '    :  6  M  M  Y 7  O "  ' 0   %  * )  &  > <  P H  $  C ?  ! L  A  $ #  ? >  P 2  Y ?  .  S 3  W 3  > *  > &  Q N  ? 7  '   N K  2  ' 6  $ 3  ( :  A 4  $ .  * <  '   = P  % 7  D  A +  > & 
Image Manipulation Methods
MethodParametersDescription
AddNoisenoise=>{Uniform, Gaussian, Multiplicative, Impulse, Laplacian,  Poisson} add noise to an image
AnnotateR text=>string, font=>string, pointsize=>integer, ; density=>geometry, box=>colorname, < pen=>colorname, geometry=>geometry, P server=>{string, @filename}, gravity=>{NorthWest, North,@ NorthEast, West, Center, East, SouthWest, South, SouthEast},. 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
Charcoalfactor=>percentagesimulate a charcoal drawing
Chopgeometry=>geometry, width=>integer, height=>integer, 3 x=>integer, y=>integerchop an image
Clonemake a copy an image
Coalescemerge a sequence of images
ColorFloodfillgeometry=>geometry, x=>integer, y=>integer, ; pen=colorname, bordercolor=colornamechanges the color value of any pixel that matches the color of theL target pixel and is a neighbor. If you specify a border color, the colorH value is changed for any neighbor pixel that is not that color.
Colorizecolor=>colorname, pen=>colornamecolorize the image with the pen color
Commentstringadd a comment to your image
Compositecompose=>{Over, In, Out, Atop, Xor, Plus, D Minus, Add, Subtract, Difference, Bumpmap, Replace, ReplaceRed, ? ReplaceGreen, ReplaceBlue, ReplaceMatte, Blend, Displace}, V image=>image-handle, geometry=>geometry, x=>integer, R y=>integer, gravity=>{NorthWest, North, NorthEast, West, Center, + East, SouthWest, South, SouthEast}composite one image onto another
Condensecompress image to take up the least amount of memory
Contrastsharpen=>{True, False}enhance or reduce the image contrast
Cropgeometry=>geometry, width=>integer, height=>integer, 3 x=>integer, y=>integercrop an image
CycleColormapamount=>integerdisplace image colormap by amount
Despecklereduce the speckles within an image
DrawJ primitive={Point, Line, Rectangle, FillRectangle, Circle, FillCircle, L Ellipse, FillEllipse, Polygon, FillPolygon, Color, Matte, Text, Image,2 @filename}, points=>string,F method={Point, Replace, Floodfill, FillToBorder, Reset}, ? pen=>colorname, bordercolor=>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, W 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
Layerlayer={Red, Green, Blue, Matte}extract a layer from the image
Magnifydouble the size of an image
Mapimage=>image-handle, dither={True, False}choose a particular set of colors from this image
MatteFloodfillgeometry=>geometry, x=>integer, y=>integer, ; matte=integer, bordercolor=colornamechanges the matte value of any pixel that matches the color of theL target pixel and is a neighbor. If you specify a border color, the matteH value is changed for any neighbor pixel that is not that color.
Minifyhalf the size of an image
Modulatebrightness=>double, saturation=>double,  hue=>doublevary the brightness, saturation, and hue of an image
Negategray=>{True, False}replace every pixel with its complementary color (white becomes black,# yellow becomes blue, etc.)
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
Quantize colors=>integer, colorspace=>{RGB, Gray, Transparent, OHTA, 8 XYZ, YCbCr, YIQ, YPbPr, YUV, CMYK}, treedepth=>O integer, dither=>{True, False}, measure_error>{True, False},+ global_colormap>{True, False}preferred number of colors in the image
Raisegeometry=>geometry, width=>integer, height=>integer, L 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, B 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
Stereoimage=>image-handlecombines two images and produces a single image thatB is the composite of a left and right image of a stereo pair
Steganoimage=>image-handle, offset=integerhide a digital watermark within the image
Swirldegrees=>doubleswirl image pixels about the center
Texturetexture=>image-handlename of texture to tile onto the image background
Thresholdthreshold=>integerthreshold the image
Transformcrop=>geometry, geometry=>geometry,L filter=>{Point, Box, Triangle, Hermite, Hanning, Hamming, Blackman,O Gaussian, Quadratic, Cubic, Catrom, Mitchell, Lanczos, Bessel, Sinc}crop or resize an image with a fully-qualified geometry specification
Transparentcolor=>colornamemake this color transparent within 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, L height=>integer, filter=>{Point, Box, Triangle, Hermite, F Hanning, Hamming, Blackman, Gaussian, Quadratic, Cubic, Catrom, + Mitchell, Lanczos, Bessel, Sinc}scale image to desired size


ANote, that the geometry parameter is a short cut for theRwidth and height parameters (e.g. geometry=>'106x80'8is 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, 



=   $image->Draw(pen=>'red', primitive=>'rectangle', ?     points=>'20,20 100,100  40,40 200,200  60,60 300,300');


Is eqivalent to



=   $image->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


KThe text parameter for methods, Annotate, Comment,NDraw, and Label can include the image filename, type, width,Nheight, or other image attribute by embedding these special format characters:

    %b   file size    %d   directory    %e   filename extention    %f   filename    %h   height    %m   magick    %p   page number    %s   scene number    %t   top of filename    %w   width    %x   x resolution    %y   y resolution    \n   newline    \r   carriage return


For example,



  text=>"%m:%f %wx%h"


B

produces an annotation of MIFF:bird.miff 512x480 for an?image titled bird.miff and whose width is 512 and heightis 480.

HYou 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

E
Use method Set to set an image attribute. For example, 



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


;And here is a list of all the image attributes you can set:

     5     !  ) <   %   N     = $   N   D  !    -   ,   #   !  M 1   <   ;  ) ;  ) )   <   <      -   $   1  > 9   F $  Z   7  H 7   *  ) ;  B '      (   6   ,   *      <  < $   5   &  ) 8 
Image Attributes
AttributeValuesDescription
adjoin{True, False}join images into a single multi-image file
antialias{True, False} remove pixel aliasing
backgroundstringimage background color
blue_primaryx-value, y-valuechromaticity blue primary point (e.g. 0.15, 0.06)
bordercolorstringset the image border color
colormap[i]stringcolor name (e.g. red) or hex value (e.g. #ccc) at position i
colorspace{RGB, CMYK}type of colorspace
compressNone, BZip, Fax, Group4, JPEG, LZW, Runlength, Ziptype of image compression
delayintegerthis many 1/100ths of a second\fP must expire before displaying the next image in a sequence
densitygeometryvertical and horizontal resolution in pixels of the image
dispose{0, 1, 2, 3, 4}GIF disposal method
dither{True, False}apply error diffusion to the image
displaystringspecifies the X server to contact
filefilehandleset the image filehandle
filenamestringset the image filename
filter{ Point, Box, Triangle, Hermite, Hanning, Hamming, Blackman, Gaussian, D Quadratic, Cubic, Catrom, Mitchell, Lanczos, Bessel, Sinc} use this filter when resizing an image
fontstringuse this font when annotating the image with text
fuzzintegercolors within this distance are considered equal
green_primaryx-value, y-valuechromaticity green primary point (e.g. 0.3, 0.6)
interlace{None, Line, Plane, Partition}the type of interlacing scheme
iterationsintegeradd Netscape loop extension to your GIF animation
loopintegeradd Netscape loop extension to your GIF animation
magickstringset the image format
matte{True, False}True if the image has transparency
mattecolorstringset the image matte color
monochrome{True, False}transform the image to black and white
page{ Letter, Tabloid, Ledger, Legal, Statement, Executive, E A3, A4, A5, B4, B5, Folio, Quarto, 10x14} or geometrypreferred size and location of an image canvas
pencolorcolor name (e.g. red) or hex value (e.g. #ccc) for annotating or changing opaque color
pixel[x, y]stringcolor name (e.g. red) or hex value (e.g. #ccc) at position (x, y)
pointsizeintegerpointsize of the Postscript or TrueType font
preview{ Rotate, Shear, Roll, Hue, Saturation, Brightness, Gamma, Spiff, P Dull, Grayscale, Quantize, Despeckle, ReduceNoise, AddNoise, Sharpen, Blur, K Threshold, EdgeDetect, Spread, Solarize, Shade, Raise, Segment, Swirl, 9 Implode, Wave, OilPaint, CharcoalDrawing, JPEG} type of preview for the Preview image format
qualityintegerJPEG/MIFF/PNG compression level
red_primaryx-value, y-valuechromaticity red primary point (e.g. 0.64, 0.33)
rendering_intent{Undefined, Saturation, Perceptual, Absolute, Relative}the type of rendering intent
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
units{ Undefined, PixelsPerInch, PixelsPerCentimeters}units of image resolution
verbose{True, False}print detailed information about the image
viewstringFlashPix viewing parameters
white_pointx-value, y-valuechromaticity white point (e.g. 0.3127, 0.329)


ANote, that the geometry parameter is a short cut for theRwidth and height parameters (e.g. geometry=>'106x80'8is 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

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



D    ($a, $b, $c) = $image->Get('colorspace', 'magick', 'adjoin');/    $width = $image->[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   .   -  P    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
colorsintegernumber of unique colors in the image
commentstringimage comment
columnsintegerimage width
depthintegerimage depth
directorystringtile names from within an image montage
filesizeintegernumber of bytes of the image on disk
formatstringget the descriptive image format
gammadoublegamma level of the image
geometrystringimage geometry
heightintegerthe number of rows or height of an image
labelstringimage label
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
tainted{True, False}True if the image has been modified
textstringany text associated with the image
type{Bilevel, Grayscale, Palette, TrueColor, MatteType, ColorSeparation }image type
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, 



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


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

          3         7   M  * 6   %  ( $   $   7   8   <   -   .   7 
Montage Parameters
ParameterValuesDescription
backgroundcolorX11 color name
borderwidthintegerimage border width
compose{Over, In, Out, Atop, Xor, Plus, Minus, Add, G Subtract, Difference, Bumpmap, Replace, MatteReplace, Mask, Blend,  Displace}composite operator
filenamestring name of montage image
fontstringX11 font 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
penstringcolor for annotation text
pointsizeintegerpointsize of the Postscript or TrueType 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 theRwidth and height parameters (e.g. geometry=>'106x80'8is 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 Methods


D
The Append method append a set of images. For example,



3    $x = $image->Append(stack=>{true,false});


Mappends all the images associated with object $image. All the inputHimages must have the same width or height. Images of the same width areLstacked top-to-bottom. Images of the same height are stacked left-to-right.MIf the stack parameter is false, rectangular images are stacked left-to-rightotherwise top-to-bottom.

H

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



    $x = $image->Average();


?averages all the images associated with object $image.

L

The Morph method morphs a set of images. Both the image pixelsMand size are linearly interpolated to give the appearance of a meta-morphosisfrom one image to the next:



5    $x = $image->Morph(frames=>integer);


Hwhere frames is the number of in-between images to generate. The default is 1.

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



#    $image->Crop('340x256+0+0');.    $image->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):



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


D

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



    $p = $image->Clone();


Gcopies all the images from object $q to $p. Use thisJmethod for multi-image sequences. PerlMagick transparently createsJa linked list from an image array. If two locations in the array point toDthe same object, the linked list goes into an infinite loop and your6script will run forever until interrupted. Instead of



    push(@$images, $image);7    push(@$images, $image);  # warning duplicate object


(use cloning to prevent an infinite loop:



    push(@$images, $image);    $clone=$image->Clone();>    push(@$images, $clone);  # same image but different object


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, 



P    ($width, $height, $size, $format) = split(',', $image->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.

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

CUse RemoteCommand to send a command to an already running Hdisplay or animateLapplication. The only parameter is the name of the image file to display oranimate.

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



G    ($red, $green, $blue) = split(', ', $image->QueryColor('cyan'));J    ($red, $green, $blue) = split(', ', $image->QueryColor('#716bae'));

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



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

    

    !    $x = $image->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   '   .   >  ! H   (   -   C   '   .   >   H   (   - 
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
315DelegateWarningan ImageMagick delegate returned a warning
320MissingDelegateWarningthe image type can not be read or written because the appropriate ' Delegate 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
415DelegateErroran ImageMagick delegate returned a warning
420MissingDelegateErrorthe image type can not be read or written because the appropriate ' Delegate is missing
425CorruptImageErrorthe image file may be corrupt
430FileOpenErrorthe image file could not be opened


@The following illustrates how you can use a numeric status code:



%    $x = $image->Read('rose.gif');    $x =~ /(\d+)/;;    die "unable to continue" if ($1 == ResourceLimitError);

#Back to Contents







Copyright

7
Copyright 1999 E. I. du Pont de Nemours and Company

K

Permission is hereby granted, free of charge, to any person obtaining aIcopy of this software and associated documentation files ("PerlMagick"), Hto deal in PerlMagick without restriction, including without limitation Ithe rights to use, copy, modify, merge, publish, distribute, sublicense, Dand/or sell copies of PerlMagick, and to permit persons to whom the FPerlMagick is furnished to do so, subject to the following conditions:

O

The above copyright notice and this permission notice shall be included in 2all copies or substantial portions of PerlMagick. 

O

The software is provided "as is", without warranty of any kind, express or Iimplied, including but not limited to the warranties of merchantability, Gfitness for a particular purpose and noninfringement.In no event shall IE. I. du Pont de Nemours and Company be liable for any claim, damages or Fother liability, whether in an action of contract, tort or otherwise, Jarising from, out of or in connection with PerlMagick or the use or other dealings in PerlMagick. 

I

Except as contained in this notice, the name of the E. I. du Pont de ENemours and Company shall not be used in advertising or otherwise to Dpromote the sale, use or other dealings in PerlMagick without prior Ewritten authorization from the E. I. du Pont de Nemours and Company. 


#Back to Contents



2Home PageIImage manipulation software that works like magic.