Perl Magick4NF,
F[Perl Magick]




Contents







Introduction

O
PerlMagick,Kversion 0.9.3, 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.FYou must have LImageMagick 3.8.2 or greater and Perl version 5.002 or greater installedMon your system. Note, this code and its documentation is Alpha, expects bugsBand problems. Send any bugs or questions to the PerlMagickOauthor. When version 1.0 is releasedJdiscussion can move to the ImageMagick mailing list, but please not before then.


*Back to Contents






Installation

H
Get the 3PerlMagick distribution and type the following:



%    gunzip -c PerlMagick-0.9.3.tar.gz     tar xvf PerlMagick-0.9.3.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. YouHare now ready to utilize the PerlMagick routines from within your Perl scripts.



*Back to Contents






PerlMagick Overview

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



    use Image::Magick;


ENext you will want to read an image or image sequence, manipulate it,Kand then write it. The input and output routines for PerlMagick are;defined in Read or Write an Image. SeeGSet an Image Attribute for routines that affect the*way an image is read or written. Refer toLManipulate an Image for a list of functions 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 Iyour images as thumbnails on a background. Finally, some routines do not=neatly fit into any of the catagories just mentioned. ReviewIMiscellaneous Routines for a list of these functions.

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 PerlLfunctions. 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;
Fand finally, to delete a single image from a multi-image sequence, use



    undef $q->[$x];

KThe next section illustrates how to use various PerlMagick functions to manipulate an image sequence.



*Back to Contents





Example Perl Magick 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;4    $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,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];H    $r->Draw(pen=>'red',primitive=>'rectangle',points=>'20,20 100,100');    $s = $q->Montage;
    undef $q;    $s->Write('x.miff');



*Back to Contents






Read or Write an Image

G
Use the functions listed below to either read, write, or display animage or image sequence. 



     ? *   B +   D = 
Read or Write Functions
RoutineParametersReturn ValueDescription
Read one or more filenamesthe number of images read and a list of any warningsread an image or image sequence
Writefilenamethe number of images written and a list of any warningswrite an image or image sequence
Displayserver namethe number of images displayed and a list of any warningsdisplay the image or image sequence on an X server


CFor convenience, each of these routines can take any parameter that5SetAttribute knows. For example,



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


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



*Back to Contents






Manipulate an Image

O
Once you create an image with, for example, function ReadImage youKmay 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");


FAnd here is a list of other image manipulation functions you can call:



    R   &  O 4  $   $ &  O   ;   ! /    O   9 0   +  ! ,  .   @  $ '    :  6  O  F  O 7  F "  $ 0   %  &  ; <  $  < ?   )  A  ! #  8 >  O 2  O ?  .  / 3  N 3  9 *  9 &  M N  U 7  $   - K  2  $ 6  ! 3  ! .  4 &  " <  " 7  $   D 
Image Manipulation Routines
RoutineParametersDescription
AddNoisenoise=>{Uniform, Gaussian, Multiplicative, Impulse, Laplacian, Poisson} add noise to an image
AnnotateJ server=>string, font=>string, pointsize=>integer,J box=>colorname, pen=>colorname, geometry=>string,I text=string, primitive={Point, Line, Rectangle, FillRectangle,M Ellipse, FillEllipse, Polygon, FillPolygon, Color, Matte, Text, Image},? center=>{true, false}, x=>integer, y=>integer annotate an image with text
Bordergeometry=>geometry, width=>integer, height=>integer, color=colornamesurround the image with a border of color
Blurfactor=>percentageblurs an image
Charcoalfactor=>percentagesimulate a charcoal drawing
Chopgeometry=>geometry, width=>integer, height=>integer,- x=>integer, y=>integerchop an image
Compositecompose=>{Over, In, Out, Atop, Xor, Plus, Minus, Add,? Subtract, Difference, Bumpmap, Replace, MatteReplace, Mask,B Blend, Displace}, image=>image-handle,x=>integer, y=>integerblurs an image
Contrastsharpen=>{true, false}enhance or reduce the image contrast
Copymake 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
Commentstringannotate an image with a comment
CycleColormapamount=>integerdisplace image colormap by amount
Despecklereduce the speckles within an image
DrawK primitive={Point, Line, Rectangle, FillRectangle, Ellipse, FillEllipse,7 Polygon, FillPolygon, Color, Matte, Text, Image},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=>double,gamma 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
Quantizecolors=>integer, treedepth=>integer, dither=>{true, false},K colorspace=>{RGB, Gray, Transparent, OHTA, XYZ, YCbCr, YCC, YIQ, YPbPr, YUV} 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
Rollx=>integer, y=>integerroll an image vertically or horizontally
Rotatedegrees=>double, crop=>{true, false}, sharpen=>{true, false}roll an image vertically or horizontally
Samplewidth=>integer, height=>integer scale image with pixel sampling
Scalewidth=>integer, height=>integer scale image to desired size
Segmentcolorspace=>{RGB, Gray, Transparent, OHTA, XYZ, YCbCr, YCC, YIQ, YPbPr,M 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
Shadecolor=>colorname, azimuth=>double, elevation=>double shade the image using a distant light source
Sharpenfactor=>percentagesharpen an image
Shearx=>double, y=>doubleshear 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
Scalewidth=>integer, height=>integer,* filter=>{Box, Mitchell, Triangle}scale image to desired size
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


HYou can optionally add Image to any routine name. For example,:TrimImage is an alias for function 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

7
Use routine Set to set an image attribute.



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


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



     5   $  K    2   D      M   =   ,   <      <  , )   <      1   2   =   +      (   6   ,   *      <   I   5 
Image Attributes
AttributeValuesDescription
adjointrue, falsejoin images into a single multi-image file
compressNo, Runlength, Ziptype of image compression
colorspace{RGB, Gray, Transparent, OHTA, XYZ, YCbCr, YCC, YIQ, YPbPr, YUV}type of colorspace
colorsintegerpreferred number of colors in the image
densitygeometryvertical and horizontal resolution in pixels of the image
disposegeometryGIF disposal method
delayintegerregulate the animation of a sequence of GIF images within Netscape
dither{true, false}apply Floyd/Steinberg error diffusion to the image
displaystringspecifies the X server to contact
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, or Partition}the type of interlacing scheme
loopintegeradd Netscape loop extension to your GIF animation
magickstringset the image format
monochrome{true, false}transform the image to black and white
numberintegerpreferred number of colors in the image
pagestringpreferred size and location of the Postscript page
pointsizeintegerpointsize of the Postscript font
qualityintegerJPEG quality setting
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
undercolorstringcontrol undercolor removal and black generation on CMYK images
verbose{true, false}print detailed information about the image


<SetAttribute is an alias for function 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

7
Use routine Get to get an image attribute.



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


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



     !     %             /      !   #      3      -      K   (   U   V   3   ?   3      2   -  :    5  $  $ 
Image Attributes
AttributeValuesDescription
backgroundstringimage background color
borderstringimage border color
class{DirectClass, PseudoClass}image class
commentstringimage comment
columnsintegerimage width
depthintegerimage depth
filesizeintegernumber of bytes of the image on disk
filenamestringname of image
foregroundstringimage foreground color
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
mattecolorstringimage matte color
meandoublethe mean error per pixel computed when an image is color reduced
monochrome{true, false}true if the image is bi-level
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
sceneintegerimage scene number
signaturestringMD5 signature associated with the image
textstringany text associated with the image
units{Undefined, pixels / inch, pixels / centimeter}units of resolution
widthintegerthe number of columns or width of an image
xintegerx resolution of the image
yintegery resolution of the image


<GetAttribute is an alias for function 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

I
Use routine 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.



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


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



             2         7   M  ) 6   $  ( $   8   <   - 
Montage Parameters
ParameterValuesDescription
backgroundstringX11 color name
bordercolorstringX11 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
fontstringX11 font name
framegeometrysurround the image with an ornamental border
geometrystringpreferred tile and border size of each tile of the composite image
gravity{NorthWest, North, NorthEast, West,6 Center, East, SouthWest, South, SouthEast }direction image gravitates to within a tile
mattecolorstringcolor of the image border
mode{Frame, Unframe, Concatenate}thumbnail framing options
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


@MontageImage is an alias for function montage.

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








%Miscellaneous Routines


I
The Average routines averages a set of images. For example,



    $x = $q->Average();


?Function Mogrify is a single entry point for the imageEmanipulation routines (Manipulate an Image). TheDparameters 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');


HYou can optionally add Image to any routine name. For example,@MontageImage is an alias for function Montage.

#Back to Contents


4[home page]IImage manipulation software that works like magic.