>K M Perl API: ImageMagick - Image Processing and Display Package * < W<8 N







  y  
>M &Contents



  y  
>M *Introduction
C
PerlMagick is an objected-oriented,Perl?interface to ImageMagick. UseHthe module to read, manipulate, or write an image or image sequence fromJwithin a Perl script. This makes it very suitable for Web CGI scripts. YouPmust have ImageMagick 5.4.3 or above and Perl version 5.005_02 or greater?installed on your system for either of these utilities to work.


O

There are a number of useful scripts available to show you the value of KPerlMagick. You can do Web based image manipulation and conversion withM MagickStudio, or use KL-systems to create images of plants using mathematical constructs, andMfinally navigate through collections of thumbnail images and select the imageMto view with the WebMagick Image Navigator.
You can try PerlMagick from your Web browser at the IImageMagick Studio. Or, you can see 7examples of select PerlMagick functions.

5 Back to Contents
 
 #  y  
>Q *Installation

UNIX

J The following instructions for Unix apply only to the unbundledJPerlMagick as obtained from CPAN. PerlMagick is included as a subdirectoryJ(PerlMagick) of the ImageMagick source distribution, and may be configuredKand built using the instructions provided in the ImageMagick distribution'sLREADME.txt file. It is usually most convenient to install PerlMagick as part$of the ImageMagick distribution.F

ImageMagick must already be installed on your system. Next,Iget the PerlMagick distribution correspondingOto the installed ImageMagick distribution (e.g. PerlMagick 5.39 for ImageMagick5.3.0) and unpack it as shown below:

    gunzip -c PerlMagick-5.39.tar.gz | tar -xvf -
    cd PerlMagick
S Next, edit Makefile.PL and change LIBS and INC to include the appropriateJpath information to the required libMagick library. You will alsoHneed paths to JPEG, PNG, TIFF, etc. delegates if they were included withMyour installed version of ImageMagick. Build and install it like this:t
    perl Makefile.PL
    make
    make install
J For Unix, you typically need to be root to install the software.OThere are ways around this. Consult the Perl manual pages for more information.

0

Windows XP / Windows 2000

J

ImageMagick must already be installed on your system. Also, theLImageMagick source distribution for Windows 2000J is required. You must also have the nmake from the Visual C++ orUJ++ development environment. Copy \bin\IMagick.dll and \bin\X11.dllO to a 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


HSee the PerlMagick Windows5HowTo page for further installation instructions.

) Running the Regression Tests

_

 To verify a correct installation, type

    make test
M Use nmake test under Windows. There are a few demonstration scriptsJavailable to exercise many of the functions PerlMagick can perform.EType
    cd demo
    make
L You are now ready to utilize the PerlMagick methods from within yourPerl scripts.


5 Back to Contents
 '   y   
>U &Overview
H
Any script that wants to use PerlMagick methods mustNfirst define the methods within its namespace and instantiate an image object.Do this with:



t
    use Image::Magick;

    $image=Image::Magick->new;
NThe new() method takes the same parameters as SetAttribute^. For example,
    $image=Image::Magick->new(size=>'384x256');
INext you will want to read an image or image sequence, manipulate it, andLthen display or write it. The input and output methods for PerlMagickOare defined in Read or Write an Image. See KSet an Image Attribute for methods that affect the way an image is readJor written. Refer to Manipulate an Image for a list ofImethods to transform an image. Get an Image AttributeO describes how to retrieve an attribute for an image. Refer to NCreate an Image Montage for details about tiling your images as thumbnailsSon a background. Finally, some methods do not neatly fit into any of the categoriesKjust mentioned. Review Miscellaneous Methods for a listof these methods.H

Once you are finished with a PerlMagick object youHshould consider destroying it. Each image in an image sequence is storedLin virtual memory. This can potentially add up to mega-bytes of memory. UponHdestroying a PerlMagick object, the memory is returned for use byIother Perl methods. The recommended way to destroy an object is with 7undef:

    undef $image;
J To delete all the images but retain the Image::Magick object use7
    @$image = ();
{ and finally, to delete a single image from a multi-image sequence, use
    undef $image->[x];
J The next section illustrates how to use various PerlMagick methods$to manipulate an image sequence.


KSome of the PerlMagick methods require external programs such as KGhostscript. This may require an explicit path in your PATH environmentpvariable to work properly. For example,
    $ENV{PATH}='/bin:/usr/bin:/usr/local/bin';






5 Back to Contents
   
 +   y   
>Y ,Example Script
C
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.png', 'logo.png', 'rose.png');
    warn "$x" if "$x";

    $x = $image->Crop(geometry=>'100x100"+1"00"+1"00');
    warn "$x" if "$x";

    $x = $image->Write('x.png');
    warn "$x" if "$x";
IThe script reads three images, crops them, and writes a single image as aNGIF animation sequence. In many cases you may want to access individual imagesof 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.png');
    $image->Read('j*.jpg');
    $image->Read('k.miff[1, 5, 3]');
    $image->Contrast();
    for ($x = 0; $image->[x]; $x++)
    {
      $image->[x]->Frame('100x200') if $image->[x]->Get('magick') eq 'GIF';
      undef $image->[x] if $image->[x]->Get('columns') < 100;
    }
    $p = $image->[1];
    $p->Draw(stroke=>'red', primitive=>'rectangle', points=>20,20 100,100');
    $q = $p->Montage();
    undef $image;
    $q->Write('x.miff');
ISuppose you want to start out with a 100 by 100 pixel white canvas with a 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');
Here we annotate an image with a Taipai TrueType font:
    $text = 'Works like magick!';
    $image->Annotate(font=>'kai.ttf', pointsize=>40, fill=>'green', text=>$text);
Other clever things you can do with a 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 object q
    @$p = ();        # delete the images but not the object p
    $p->Convolve([1, 2, 1, 2, 4, 2, 1, 2, 1]);   # 3x3 Gaussian kernel


5 Back to Contents
   
# /   y   
>] 4Read or Write an Image
H
Use the methods listed below to either read, write,+or display an image or image sequence.



& 2         * *     - +     / =     . 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
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
Q

For convenience, methods Write(), Display(), and Animate()Ican take any parameter that SetAttribute knows about.nFor example,

    $image->Write(filename=>'image.png', compression=>'None');
I Use - as the filename to method Read() to read from standard inor to method Write() to write to standard out:
    binmode STDOUT;
    $image->Write('png:-');
 To read an image in the GIF format from a PERL filehandle, use:
    $image = Image::Magick->new;
    open(IMAGE, 'image.gif');
    $image->Read(file=>\*IMAGE);
    close(IMAGE);
 To write an image in the PNG format to a PERL filehandle, use:
    $filename = "image.png";
    open(IMAGE, ">$filename");
    $image->Write(file=>\*IMAGE, filename=>$filename);
    close(IMAGE);
JIf %0Nd, %0No, or %0Nx appears in the filename, it is interpretedKas a printf format specification and the specification is replaced with theJspecified decimal, octal, or hexadecimal encoding of the scene number. For example,


    image%03d.miff


1converts files image000.miff, image001.miff, etc.

H

You can optionally add Image to any methodAname. For example, ReadImage() is an alias for method Read().


!
< Back to Contents  
 
' 3   y   
>a 1Manipulate an Image
K
Once you create an image with, for example, methodKReadImage() you may want to operate on it. Below is a list of all the imageHmanipulations methods available to you with PerlMagick. There areM examples of selectH PerlMagick methods. Here is an example call%to an image manipulation method:

"

    $image->Crop(geometry=>'100x100"+1"0+20');
    $image->[x]->Frame("100x200");
HAnd here is a list of other image manipulation methods you can call:

* 7       U   . !    O K    K N    L 4    M +    # &    L     %    E    N O    : 1     &    ( -    % +    $ /    8 J    L     $ ,    >    .    H @    # K    K Q    :    6    '    K    K    L 7    M "    # 0     %    ? -    &   B <    N O    # V    $    M K    K N   ! L    A    $ #    ] ?    H 2    4 2    L ?    # O    L J    S 3        L *    L &    I J    P 7    K Q    N ,    L K    H    ' 6    $ 3    ( M    C 4    $ .    * <    &     ? 7    D    K =    S +  "
Image Manipulation Methods
MethodParametersDescription
AddNoisenoise=>{Uniform, Gaussian, Multiplicative, Impulse, Laplacian, Poisson} add noise to an image
AffineTransformaffine=>array of float values,E translate=>float, float, scale=> float, float,P rotate=>float, skewX=>float, skewY=>floataffine transform image
Annotatetext=>string, font=>string, family=>string,+ style=>{Normal, Italic, Oblique, Any},A stretch=>{Normal, UltraCondensed, ExtraCondensed, Condensed,I SemiCondensed, SemiExpanded, Expanded, ExtraExpanded, UltraExpanded},: weight=>integer, pointsize=>integer,- density=>geometry, stroke=>J color name, strokewidth=>integer,6 fill=>color name,< undercolor=>color name, geometry=>geometry,J gravity=>{NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast},J antialias=>{true, false}, x=>integer, y=>integer,) affine=>array of float values,C translate=>float, float, scale=>float, float,K rotate=>float. skewX=>float, skewY=> float,! align=>{Left, Center, Right}, encoding=>{UTF-8} annotate an image with text. See QueryFontMetrics5 to get font metrics without rendering any text.
Blurgeometry=>geometry, radius=>double, sigma=>doubleblur the image with a Gaussian operator of the given radius and standarddeviation (sigma).
Bordergeometry=>geometry, width=>integer, height=>Einteger, fill=>color namesurround the image with a border of color
Channelchannel=>{Red, Cyan, Green, Magenta, Blue, Yellow, Opacity, Black}extract a channel from the image
Charcoalorder=>integersimulate a charcoal drawing
Chopgeometry=>geometry, width=>integer, height=><integer, x=>integer, y=>integerchop an image
Coalesce
#
merge a sequence of images
Clip
#
apply any clipping path information as an image clip mask.
ColorFloodfillgeometry=>geometry, x=>integer, y=>integer_, fill=>color name, bordercolor=>color namechanges the color value of any pixel that matches the color of the targetJpixel and is a neighbor. If you specify a border color, the color value is;changed for any neighbor pixel that is not that color.
Colorizefill=>color name,% opacity=>stringcolorize the image with the fill color
Commentstringadd a comment to your image
Compareimage=>image-handlecompare image to a reference image
Composite image=>image-handle,D compose=>{Over, In, Out, Atop, Xor, Plus, Minus, Add, Subtract,F Difference, Multiply, Bumpmap, Copy, CopyRed, CopyGreen, CopyBlue,? CopyMatte, Dissolve, Clear, Displace, Modulate, Threshold},? mask=>image-handle, geometry=>geometry,/ x=>integer, y=>integer,L gravity=>{NorthWest, North, NorthEast, West, Center, East, SouthWest,N South, SouthEast}, opacity=>integer, tile=>{True, False},N rotate=>double, color=>color name composite one image onto another
Contrastsharpen=>{True, False}enhance or reduce the image contrast
Convolvecoefficients=>array of float valuesapply a convolution kernel to the image. Given a kernel orderT, you would supply order*order float values (e.g. 3x3 implies 9 values).
Cropgeometry=>geometry, width=>integer, height=><integer, x=>integer, y=>integercrop an image
CycleColormapamount=>integerdisplace image colormap by amount
Deconstruct
#
break down an image sequence into constituent parts
Despeckle
#
reduce the speckles within an image
Drawprimitive=>{point, line, rectangle, arc, ellipse, circle, path,E polyline, polygon, bezier, color, matte, text, @filename},H points=>string , method=>{Point, Replace, Floodfill,A FillToBorder, Reset}, stroke=>Hcolor name, fill=>color name,Ptile=>image-handle, strokewidth=>float, antialias=>{true,Mfalse}, bordercolor=>color name, x=>Gfloat, y=>float, affine=>array of float values,0translate=>float, float, scale=>Pfloat, float, rotate=>float. skewX=>float, skewY=>floatannotate an image with one or more graphic primitives
Edgeradius=>doubleenhance edges within the image with a convolution filter of the given radius.
Embossgeometry=>geometry, radius=>double, sigma=>doubleemboss the image with a convolution filter of the given radius and standarddeviation (sigma).
Enhance
#
apply a digital filter to enhance a noisy image
Equalize
#
perform histogram equalization to the image
Flatten
#
flatten a sequence of images
Flip
#
create a mirror image by reflecting the image scanlines in thevertical direction
Flop
#
create a mirror image by reflecting the image scanlines in thehorizontal direction
Framegeometry=>geometry, width=>integer, height=>binteger, inner=>integer, outer=>integer, fill=>color namesurround the image with an ornamental border
Gammagamma=>string, red=>double, green=>double, blue=>doublegamma correct the image
Implodeamount=>doubleimplode image pixels about the center
Labelstringassign a label to an image
Levellevel=>string, 'black-point'=>double,G 'mid-point'=>double, 'white-point'=>doubleadjust the level of image contrast
Magnify
#
double 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=>color namechanges the matte value of any pixel that matches the color of the targetJpixel and is a neighbor. If you specify a border color, the matte value is;changed for any neighbor pixel that is not that color.
MedianFilterradius=>doublereplace each pixel with the median intensity pixel of a neighborhood. 
Minify
#
half the size of an image
Modulatebrightness=>double, saturation=>double, hue=>doublevary the brightness, saturation, and hue of an image by the specifiedpercentage
MotionBlurgeometry=>geometry, radius=>double, sigma=>*double, angle=>doubleblur the image with a Gaussian operator of the given radius and standardJdeviation (sigma) at the given angle to simulate the effect of motion
Negategray=>{True, False}replace every pixel with its complementary color (white becomes black,yellow becomes blue, etc.)
Normalize
#
transform image to span the full range of color values
OilPaintradius=>integersimulate an oil painting
Opaquecolor=>color name, fill=>color namechange this color to the fill color within the image
Quantizecolors=>integer, colorspace=>{RGB, Gray, Transparent,HOHTA, XYZ, YCbCr, YIQ, YPbPr, YUV, CMYK}, treedepth=> integer,Udither=>{True, False}, measure_error=>{True, False}, global_colormap=>{True, False}preferred number of colors in the image
Profilename=>{ICM, IPTC}, profile=>blobadd or remove ICC or IPTC image profile
Raisegeometry=>geometry, width=>integer, height=>Iinteger, x=>integer, y=>integer, raise=>{True, False}lighten or darken image edges to create a 3-D effect
ReduceNoiseradius=>doublereduce noise in the image with a noise peak elimination filter 
Resizegeometry=>geometry, width=>integer, height=>Iinteger, filter=>{Point, Box, Triangle, Hermite, Hanning, Hamming,HBlackman, Gaussian, Quadratic, Cubic, Catrom, Mitchell, Lanczos, Bessel,"Sinc}, blur=>doublescale image to desired size. Specify blur > 1 for blurryor < 1 for sharp
Rollgeometry=>geometry, x=>integer, y=>integerroll an image vertically or horizontally
Rotate degrees=>double,> color=>color name rotate an image
Samplegeometry=>geometry, width=>integer, height=>integerscale image with pixel sampling
Scalegeometry=>geometry, width=>integer, height=>integerscale image to desired size
Segmentcolorspace=>{RGB, Gray, Transparent, OHTA, XYZ, YCbCr, YCC, YIQ,OYPbPr, YUV, CMYK}, verbose={True, False}, cluster=>double, smooth=doublesegment an image by analyzing the histograms of the color components/and identifying units that are homogeneous
Shadegeometry=>geometry, azimuth=>double, elevation=>-double, gray=>{true, false} shade the image using a distant light source
Sharpengeometry=>geometry, radius=>double, sigma=>doublesharpen the image with a Gaussian operator of the given radius and standarddeviation (sigma).
Shavegeometry=>geometry, width=>integer, height=>integer shave pixels from the image edges
Sheargeometry=>geometry, x=>double, y=>double> color=>color name shear the image along the X or Y axis by a positive or negative shear angle
Signature
#
generate an SHA-256 message digest for the image pixel stream
Solarizethreshold=>integernegate all pixels above the threshold level
Spreadamount=>integerdisplace image pixels by a random amount
Stereoimage=>image-handlecomposites two images and produces a single image that 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=>stringthreshold the image
Transparentcolor=>color namemake this color transparent within the image
Trim
#
remove edges that are the background color from the image
UnsharpMaskgeometry=>geometry, radius=>double, sigma=>Fdouble, amount=>double, threshold=>doublesharpen the image with the unsharp mask algorithm.
Wavegeometry=>geometry, amplitude=>double, wavelength=>doublealter an image along a sine wave
H

Note, that the geometry parameter isLa short cut for the width and height parameters (e.g. Qgeometry=>'106x80' is equivalent to width=>106, height=>80).

P

You can specify @filename in both Annotate()Hand Draw(). This reads the text or graphic primitive instructions from afile on disk. For example,

   $image->Draw(fill=>'red', primitive=>'rectangle', 
     points=>'20,20 100,100  40,40 200,200  60,60 300,300');
e Is equivalent to
   $image->Draw(fill=>'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
J The text parameter for methods, Annotate(), Comment(), Draw(), andKLabel() can include the image filename, type, width, height, or other imageattribute by embedding these special format characters:
    %b   file size
    %d   comment
    %d   directory
    %e   filename extension
    %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
6 For example,
  text=>"%m:%f %wx%h"



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

You can optionally add Image to any methodBname. For example, TrimImage() is an alias for method Trim().

M

Most of the attributes listed above have an analogPin convert. See the documentation for a more detailed$description of these attributes.


%
5 Back to Contents
   
+ 7  y  "
>e 4Set an Image Attribute
H
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        ,    5 !    ) <    5 %     0    5 N         '    G $    Y 0     I     D     /    9      -     ,     #     !     M     <     ;     #    ?    ) ;   #  :    ) )     <    %     <          -    5 $     .     1     1    I 9   #  A     7    M 7     *    ) ;    B '     2          (     6     ,     *     @          <    L     < $     5    ) #    ) 8  & $
Image Attributes
AttributeValuesDescription
adjoin{True, False}join images into a single multi-image file
antialias{True, False} remove pixel aliasing
authenticatestringdecrypt image with this password.
backgroundcolor nameimage background color
blue-primaryx-value, y-valuechromaticity blue primary point (e.g. 0.15, 0.06)
bordercolorcolor nameset the image border color
clip-maskimageAssociate a clip mask with the image.
colormap[i]color namecolor name (e.g. red) or hex value (e.g. #ccc) at position i
colorspace{RGB, CMYK}type of colorspace
commentstringAppend to the image comment.
compression{None, BZip, Fax, Group4, JPEG, LosslessJPEG, LZW, RLE, Zip}type of image compression
debug{No, Configure, Annotate, Render, Locale, Coder, X11, Cache, Blob, All}display copious debugging information
delayintegerthis many 1/100ths of a second\fP must expire before displaying thenext image in a sequence
densitygeometryvertical and horizontal resolution in pixels of the image
disk-limitintegerset disk resource limit in megabytes
dispose{Undefined, None, Background, Previous}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
fillcolorThe fill color paints any areas inside the outline of drawn shape.
fontstringuse this font when annotating the image with text
fuzzintegercolors within this distance are considered equal
gammadoublegamma level of the image
Gravity{Forget, NorthWest, North, NorthEast, West, Center, East,% SouthWest, South, SouthEast} type of image gravity
green-primaryx-value, y-valuechromaticity green primary point (e.g. 0.3, 0.6)
index[x, y]stringcolormap index at position (x, y)
interlace{None, Line, Plane, Partition}the type of interlacing scheme
iterationsintegeradd Netscape loop extension to your GIF animation
labelstringAppend to the image label.
loopintegeradd Netscape loop extension to your GIF animation
magickstringset the image format
matte{True, False}True if the image has transparency
mattecolorcolor nameset the image matte color
map-limitintegerset map resource limit in megabytes
memory-limitintegerset memory resource limit in megabytes
monochrome{True, False}transform the image to black and white
page{ Letter, Tabloid, Ledger, Legal, Statement, Executive, A3, A4, A5,5B4, B5, Folio, Quarto, 10x14} or geometrypreferred size and location of an image canvas
pixel[x, y]stringhex value (e.g. #ccc) at position (x, y)
pointsizeintegerpointsize of the Postscript or TrueType font
preview{ Rotate, Shear, Roll, Hue, Saturation, Brightness, Gamma, Spiff, Dull,PGrayscale, Quantize, Despeckle, ReduceNoise, AddNoise, Sharpen, Blur, Threshold,JEdgeDetect, Spread, Solarize, Shade, Raise, Segment, Swirl, 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
sampling-factorgeometryhorizontal and vertical sampling factor
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
strokecolorThe stroke color paints along the outline of a shape.
tilestringtile name
texturestringname of texture to tile onto the image background
type{Bilevel, Grayscale, GrayscaleMatte, Palette, PaletteMatte, TrueColor,FTrueColorMatte, ColorSeparation, ColorSeparationMatte, Optimize }image type
units{ Undefined, PixelsPerInch, PixelsPerCentimeters}units of image resolution
verbose{True, False}print detailed information about the image
virtual-pixel{Constant, Edge, Mirror, Tile}the virtual pixel method
white-pointx-value, y-valuechromaticity white point (e.g. 0.3127, 0.329)
I

Note, that the geometry parameterJis a short cut for the width and height parameters (e.g.K geometry=>'106x80' is equivalent toH width=>106, height=>80).

K

SetAttribute() is an alias for method Set().

J

Most of the attributes listed above have anIanalog in convert. See the documentation for a2more detailed description of these attributes.

!
)
. Back to Contents
   
/ ;  $ y  & $
>i 4Get an Image Attribute
L
Use method Get() to get an image attribute.For example,
#
*
$
    ($a, $b, $c) = $image->Get('colorspace', 'magick', 'adjoin');
    $width = $image->[3]->Get('columns');
VIn addition to all the attributes listed in Set an Image Attribute., you can get these additional attributes:
$
2 - (        4     7     5          /                    2     >     /     +          3    "          H     I     7     3     H     .     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
errordoublethe mean error per pixel computed with methods Compare() or Quantize()
filesizeintegernumber of bytes of the image on disk
formatstringget the descriptive image format
geometrystringimage geometry
heightintegerthe number of rows or height of an image
idintegerImageMagick registry id
labelstringimage label
maximum-errordoublethe normalized max error per pixel computed with methods Compare() or Quantize()
mean-errordoublethe normalized mean error per pixel computed with methods Compare() or Quantize()
montagegeometrytile size and offset within an image montage
rowsintegerthe number of rows or height of an image
signaturestringSHA-256 message digest associated with the image pixel stream
taint{True, False}True if the image has been modified
widthintegerthe number of columns or width of an image
x-resolutionintegerx resolution of the image
y-resolutionintegery resolution of the image
H

GetAttribute() is an alias for method Get().

K

Most of the attributes listed above haveJan analog in convert. See the documentation for4a more detailed description of these attributes.

%
-
. Back to Contents
   $
3 ?  ( y  * (
>m 5Create an Image Montage
O
Use method Montage() to create a compositeQimage by combining several separate images. The images are tiled on the compositeOimage with the name of the image optionally appearing just below the individualtile. For example,
'
.
(
    $image->Montage(geometry=>'160x160', tile=>'2x2', texture=>'granite:');
;And here is a list of Montage() parameters you can set:
(
6 / ,       5         Q         . %          7     M    I 6    $     '     %    ( $     7     8    . '     <     -     .     7  . ,
Montage Parameters
ParameterValuesDescription
backgroundcolor name background color name
borderwidthintegerimage border width
compose{Over, In, Out, Atop, Xor, Plus, Minus, Add, Subtract, Difference, Bumpmap,+Copy, Mask, Dissolve, Clear, Displace}composite operator
filenamestring name of montage image
fillcolor namefill color for annotations
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, Center, East, SouthWest, South,SouthEast}direction image gravitates to within a tile
ICMblobcolor information profile
IPTCblobnewswire information profile
labelstringassign a label to an image
mode{Frame, Unframe, Concatenate}thumbnail framing options
pointsizeintegerpointsize of the Postscript or TrueType font
shadow{True, False}add a shadow beneath a tile to simulate depth
strokecolor namestroke color for annotations
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
Q

Note, that the geometry parameterJis a short cut for the width and height parameters (e.g.P geometry=>'106x80' is equivalent/to width=>106, height=>80).

L

MontageImage() is an alias for methodMontage().

J

Most of the attributes listed aboveKhave an analog in montage. See the documentation8for a more detailed description of these attributes.

)
1
; Back to Contents  
 (
8 C  , y  . ,
>q 0Working with Blobs
K
A blob contains data that directlySrepresent a particular image format in memory instead of on disk. PerlMagickH supports blobs in any of these image formatsQand provides methods to convert a blob to or from a particular image format.
+
2
,
: ) 0        2 @ B     4 0  2 0
Blob Methods
MethodParametersReturn ValueDescription
ImageToBlobany image attributean array of image data in the respective image formatconvert an image or image sequence to an array of blobs
BlobToImageone or more blobsthe number of blobs converted to an imageconvert one or more blobs to an image
-
IImageToBlob() 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 it to a display program:
    @blobs = $image->ImageToBlob();
    open(DISPLAY,"| display -") || die;
    binmode DISPLAY;
    print DISPLAY $blobs[0];
    close DISPLAY;
K Method BlobToImage() returns an image or image sequence converted from thesupplied blob:
    @blob=$db->GetImage();
    $image=Image::Magick->new(magick=>'jpg');
    $image->BlobToImage(@blob);
,
5
,
0

-
. Back to Contents
   ,
; G  0 y  2 0
>u 3Miscellaneous Methods
I
The Append() method append a set of images. For example,
/
6
0
y
    $p = $image->Append(stack=>{true,false});
>appends all the images associated with object $image.DBy default, images are stacked left-to-right. Set stack to!True to stack them top-to-bottom.L

The Average() method averagesVa set of images. For example,

    $p = $image->Average();
E averages all the images associated with object $image.

H

The Clone() method copiesTa set of images. For example,

    $p = $image->Clone();
J copies all the images from object $q to $p. You can use5this method for single or multi-image sequences.

H

The Morph() method morphsIa set of images. Both the image pixels and size are linearly interpolatedto give the appearance of a meta-morphosis from one image to the next:

    $p = $image->Morph(frames=>integer);
P where frames is the number of in-between images to generate. The default is 1.

I

Mosaic() creates an mosaicfrom an image sequence.

K

Method Mogrify() is a singleJentry point for the image manipulation methods (ManipulateQan Image). The parameters are the name of a method followed by any parametersthe method may require. For example, these calls are equivalent:

    $image->Crop('340x256+0+0');
    $image->Mogrify('crop', '340x256+0+0');
H Method MogrifyRegion() applies a transform to a region of the image. ItIis similar to Mogrify() but begins with the region geometry. For example,Lsuppose you want to brighten a 100x100 region of your image at location (40,l50):
    $image->MogrifyRegion('100x100+40+50', 'modulate', brightness=>50);


@Ping() is a convenience method that returns information about anCimage without having to read the image into memory. It returns theDwidth, height, file size in bytes, and the file format of the image.?You can specify more than one filename but only one filehandle:
   B  ($width, $height, $size, $format) = $image->Ping('logo.png');H  ($width, $height, $size, $format) = $image->Ping(file=>\*IMAGE);F  ($width, $height, $size, $format) = $image->Ping(blob=>$blob);
KThis is a more efficient and less memory intensive way to query if an image(exists and what its characteristics are.J

To have full control overtext positioning you need font metric information. Use

    ($x_ppem, $y_ppem, $ascender, $descender, $width, $height, $max_advance) =
     $image->QueryFontMetrics(parameters);
M Where parameters is any parameter of the Annotate# method. The return values are

6

2 6

3
L Call QueryColor() with no parameters to return a list of known colors namesMor specify one or more color names to get these attributes: red, green, blue,and opacity value.
2
'

    @colors = $image->QueryColor();
    ($red, $green, $blue, $opacity) = $image->QueryColor('cyan');
    ($red, $green, $blue, $opacity) = $image->QueryColor('#716bae');


3
J QueryColorName() accepts a color value and returns its respective name orhex value;
2
      $name = $image->QueryColorName('rgba(80,60,0,0)');
6

3
O Call QueryFont() with no parameters to return a list of known fonts or specifyGone or more font names to get these attributes: font name, description,Cfamily, style, stretch, weight, encoding, foundry, format, metrics,and glyphs values.
2

    @fonts = $image->QueryFont();
    $weight = ($image->QueryFont('Helvetica'))[5];


6

3
N Call QueryFormat() with no parameters to return a list of known image formatsIor specify one or more format names to get these attributes: adjoin, blob=support, raw, decoder, encoder, description, and module.
2

    @formats = $image->QueryFormat();
    ($adjoin, $blob_support, $raw, $decoder, $encoder, $description, $module) = $image->QueryFormat('gif');


H

Use RemoteCommand() toJsend a command to an already running display orP animateI application. The only parameter is the name of the image file to displayor animate.

I

Finally, the Transform()Pmethod accepts a fully-qualified geometry specification for cropping or resizingmone or more images. For example,

    $p = $image->Transform(crop=>'100x100');
K You can optionally add Image to any method name above. For example,.PingImage() is an alias for method Ping().

3
;
. Back to Contents
   2
A M  6 y  8 6
>{ -Handling Errors
H
All PerlMagickHmethods return an undefined string context upon success. If any problemsHoccur, the error is returned as a string with an embedded numeric statusMcode. A status code less than 400 is a warning. This means that the operationKdid not complete but was recoverable to some degree. A numeric code greaterJor equal to 400 is an error and indicates the operation failed completely.?Here is how errors are returned for the different methods:
5
4
4 5
<
6
cHere is an example error message:
    Error 400: Memory allocation failed
+Below is a list of error and warning codes:

D 4 :       7    C    B    .    <   ! K    (    -    7    ?    7    '    3    >    ;    C    B    .    <    K    (    -    7    ?    7    '    -    >    ;  < :
Error and Warning Codes
CodeMnemonicDescription
0Successmethod completed without an error or warning
300ResourceLimitWarninga program resource is exhausted (e.g. not enough memory)
305TypeWarningA font is unavailable; a substitution may have occurred
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
335BlobWarninga binary large object could not be allocated
340StreamWarningthere was a problem reading or writing from a stream
345CacheWarningpixels could not be saved to the pixel cache
380XServerWarningan X resource is unavailable
385MonitorWarningthere was a problem with prgress monitor
390RegistryWarningthere was a problem getting or setting the registry
395ConfigureWarningthere was a problem getting a configuration file
400ResourceLimitErrora program resource is exhausted (e.g. not enough memory)
405TypeErrorA font is unavailable; a substitution may have occurred
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
435BlobErrora binary large object could not be allocated
440StreamErrorthere was a problem reading or writing from a stream
445CacheErrorpixels could not be saved to the pixel cache
480XServerErroran X resource is unavailable
480MonitorErrorthere was a progress monitor error
490RegistryErrorthere was a problem getting or setting the registry
495ConfigureErrorthere was a problem getting a configuration file
7

The following illustrates how you can use a numeric status code:
    $x = $image->Read('rose.png');
    $x =~ /(\d+)/;
    die "unable to continue" if ($1 == ResourceLimitError);
6
?
6
:

7
. Back to Contents
   6
E Q  : y  < :
> 'Copyright
L
Copyright (C) 2002ImageMagick Studio
<

I
Permission isOhereby granted, free of charge, to any person obtaining a copy of this softwareHand associated documentation files ("PerlMagick"), to deal in PerlMagickJwithout restriction, including without limitation the rights to use, copy,Qmodify, merge, publish, distribute, sublicense, and/or sell copies of PerlMagick,Kand to permit persons to whom the PerlMagick is furnished to do so, subject%to the following conditions:
>

Q
The above copyrightPnotice and this permission notice shall be included in all copies or substantial portions of PerlMagick.
@

L
The softwarePis provided "as is", without warranty of any kind, express or implied, includingNbut not limited to the warranties of merchantability, fitness for a particularJpurpose and noninfringement.In no event shall ImageMagick Studio be liableLfor any claim, damages or other liability, whether in an action of contract,Htort or otherwise, arising from, out of or in connection with PerlMagick4or the use or other dealings in PerlMagick.
B

H
ExceptCas contained in this notice, the name of the ImageMagick Studio LLCBshall not be used in advertising or otherwise to promote the sale,Luse or other dealings in PerlMagick without prior written authorization from the ImageMagick Studio.
A
) Back to Contents@
>

9Image manipulation software that works like magic.