PerlMagick is an object-oriented Perl interface to ImageMagick. Use the module to read, manipulate, or write an image or image sequence from within a Perl script, making it well suited for Web CGI scripts. ImageMagick 6.5.5 or above and Perl version 5.005_02 or greater are required for PerlMagick to build properly.
Several useful scripts demonstrate the capabilities of PerlMagick: perform Web-based image manipulation and conversion with MagickStudio, generate plant images using mathematical constructs with L-systems, or browse collections of thumbnail images with the WebMagick Image Navigator.
You can also try PerlMagick directly in your Web browser at ImageMagick Studio, or explore examples of select PerlMagick functions.
Installation
UNIX
Check if PerlMagick is available from your system package repository. For example, on CentOS systems, install it with:
yum install ImageMagick-perl
Otherwise, install PerlMagick from the ImageMagick source distribution. Download the latest source release and unpack it:
tar xvzf ImageMagick.tar.gz
Configure and compile ImageMagick with Perl support:
cd ImageMagick-7.1.2-36
./configure -with-perl
make
Once compiled without errors, install it (administrator privileges required) and update the dynamic linker run-time bindings:
sudo make install
sudo ldconfig /usr/local/lib
Verify that PerlMagick is properly installed:
perl -MImage::Magick -le 'print Image::Magick->QuantumDepth'
You are now ready to use PerlMagick to convert, compose, or edit your images.
Windows XP / Windows 2000
ImageMagick must already be installed along with the ImageMagick source distribution for Windows 2000 and nmake from the Visual C++ or J++ development environment. Copy \bin\IMagick.dll and \bin\X11.dll to a directory in your dynamic load path such as c:\perl\site\5.00502, then build and install:
cd PerlMagick
perl Makefile.nt
nmake
nmake install
Running the Regression Tests
To verify a correct installation, run the test suite (use nmake test under Windows):
make test
You can also use the prove utility to run an individual test from the build folder, or build the included demonstration scripts:
prove --blib blib -I `pwd` -bv ./t/read.t
cd demo
make
You are now ready to utilize PerlMagick methods within your Perl scripts.
Overview
Any script that uses PerlMagick methods must first import the Image::Magick namespace and instantiate an image object:
use Image::Magick;
$image = Image::Magick->new;
PerlMagick is quantum aware. You can request a specific quantum depth when instantiating an image object:
use Image::Magick::Q16;
$image = Image::Magick::Q16->new;
The new() method accepts the same parameters as SetAttribute. For example:
$image = Image::Magick->new(size=>'384x256');
Typical workflows involve reading an image or image sequence, manipulating it, and displaying or writing the result. Input and output methods are covered in Read or Write an Image, while Set an Image Attribute and Get an Image Attribute control and inspect image properties. Refer to Manipulate an Image for image transformations, Create an Image Montage for tiling thumbnails onto a background, and Miscellaneous Methods for additional utilities.
Because each image in a sequence is stored in virtual memory—potentially consuming mebibytes of RAM—you should destroy PerlMagick objects when finished to free memory for other Perl operations. Use undef to destroy the entire object:
undef $image;
To delete all images while retaining the Image::Magick object, use:
@$image = ();
To delete a single image from a multi-image sequence, use:
undef $image->[$x];
Some PerlMagick methods rely on external delegates such as Ghostscript, which may require adding their directory to your PATH environment variable (for example, in Linux):
$ENV{PATH} = '/../bin:/usr/bin:/usr/local/bin';
Example Script
Here is a basic 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+100+100');
warn "$x" if "$x";
$x = $image->Write('x.png');
warn "$x" if "$x";
This script reads three images, crops them, and writes the resulting sequence. You can also access and manipulate individual frames within a sequence:
#!/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');
To create a 100×100 pixel white canvas with a red pixel in the center:
$image = Image::Magick->new;
$image->Set(size=>'100x100');
$image->ReadImage('canvas:white');
$image->Set('pixel[49,49]'=>'red');
To reduce the red component intensity at (1,1) by half:
@pixels = $image->GetPixel(x=>1,y=>1);
$pixels[0]*=0.5;
$image->SetPixel(x=>1,y=>1,color=>\@pixels);
To convert a color image to grayscale:
$image->Quantize(colorspace=>'gray');
To annotate an image with a Taipei TrueType font:
$text = 'Works like magick!';
$image->Annotate(font=>'kai.ttf', pointsize=>40, fill=>'green', text=>$text);
To extract all pixel intensities from an image and write them to STDOUT:
@pixels = $image->GetPixels(map=>'I', height=>$height, width=>$width, normalize=>true);
binmode STDOUT;
print pack('B*',join('',@pixels));
Other useful operations on PerlMagick image sequences 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
Read or Write an Image
Use the methods listed below to read, write, or display an image or image sequence:
| Method | Parameters | Return Value | Description |
|---|---|---|---|
Read |
one or more filenames | the number of images read | read an image or image sequence |
Write |
filename | the number of images written | write an image or image sequence |
Display |
server name | the number of images displayed | display the image or image sequence to an X server |
Animate |
server name | the number of images animated | animate image sequence to an X server |
For convenience, Write(), Display(), and Animate() accept any parameter supported by SetAttribute. For example:
$image->Write(filename=>'image.png', compression=>'None');
Use - as the filename to Read() from standard input or Write() to standard output:
binmode STDOUT;
$image->Write('png:-');
To read a GIF image from a Perl filehandle:
$image = Image::Magick->new;
open(IMAGE, 'image.gif');
$image->Read(file=>\*IMAGE);
close(IMAGE);
To write a PNG image to a Perl filehandle:
$filename = "image.png";
open(IMAGE, ">$filename");
$image->Write(file=>\*IMAGE, filename=>$filename);
close(IMAGE);
Note that reading from or writing to a Perl filehandle may fail under Windows due to mismatched C-runtime library versions between ImageMagick and ActiveState Perl distributions, or if a DLL is linked with /MT. See Potential Errors Passing CRT Objects Across DLL Boundaries for details.
If %0Nd, %0No, or %0Nx appears in the filename, it is interpreted as a printf format specification and replaced with the decimal, octal, or hexadecimal scene number. For example, image%03d.miff writes files image000.miff, image001.miff, etc.
You can optionally append Image to any method name (for example, ReadImage() is an alias for Read()).
Manipulate an Image
Once an image is loaded (for instance, via ReadImage()), you can apply any of the image manipulation methods listed below. See examples for sample usage. Example calls:
$image->Crop(geometry=>'100x100+10+20');
$image->[$x]->Frame("100x200");
| Method | Parameters | Description |
|---|---|---|
AdaptiveBlur |
geometry=>geometry, radius=>double, sigma=>double, bias=>double, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | adaptively blur the image with a Gaussian operator of the given radius and standard deviation (sigma). Decrease the effect near edges. |
AdaptiveResize |
geometry=>geometry, width=>integer, height=>integer, filter=>{Point, Box, Triangle, Hermite, Hanning, Hamming, Blackman, Gaussian, Quadratic, Cubic, Catrom, Mitchell, Lanczos, Bessel, Sinc}, support=>double, blur=>double | adaptively resize image using data dependant triangulation. Specify blur > 1 for blurry or < 1 for sharp |
AdaptiveSharpen |
geometry=>geometry, radius=>double, sigma=>double, bias=>double, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | adaptively sharpen the image with a Gaussian operator of the given radius and standard deviation (sigma). Increase the effect near edges. |
AdaptiveThreshold |
geometry=>geometry, width=>integer, height=>integer, bias=>double | local adaptive thresholding. |
AddNoise |
noise=>{Uniform, Gaussian, Multiplicative, Impulse, Laplacian, Poisson}, attenuate=>double, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | add noise to an image |
AffineTransform |
affine=>array of float values, translate=>float, float, scale=> float, float, rotate=>float, skewX=>float, skewY=>float, interpolate={Average, Bicubic, Bilinear, Filter, Integer, Mesh, NearestNeighbor}, background=>color name | affine transform image |
Affinity |
image=>image-handle, method=>{None, FloydSteinberg, Riemersma} | choose a particular set of colors from this image |
Annotate |
text=>string, font=>string, family=>string, style=>{Normal, Italic, Oblique, Any}, stretch=>{Normal, UltraCondensed, ExtraCondensed, Condensed, SemiCondensed, SemiExpanded, Expanded, ExtraExpanded, UltraExpanded}, weight=>integer, pointsize=>integer, density=>geometry, stroke=>color name, strokewidth=>integer, fill=>color name, undercolor=>color name, kerning=>float, geometry=>geometry, gravity=>{NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast}, antialias=>{true, false}, x=>integer, y=>integer, affine=>array of float values, translate=>float, float, scale=>float, float, rotate=>float. skewX=>float, skewY=> float, align=>{Left, Center, Right}, encoding=>{UTF-8}, interline-spacing=>double, interword-spacing=>double, direction=>{right-to-left, left-to-right}, decorate=>{none, underline, overline, line-through}, word-break=>{normal, break-word} | annotate an image with text. See QueryFontMetrics to get font metrics without rendering any text. |
AutoGamma |
channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | automagically adjust gamma level of image |
AutoLevel |
channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | automagically adjust color levels of image |
AutoOrient |
- | adjusts an image so that its orientation is suitable for viewing (i.e. top-left orientation) |
AutoThreshold |
method=>{Kapur, OTSU, Triangle} | automatically perform image thresholding |
BilateralSmoothing |
geometry=>geometry, width=>integer, height=>integer, intensity-sigma=>double, spatial-sigma=>double, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | a non-linear, edge-preserving, and noise-reducing smoothing filter for images. It replaces the intensity of each pixel with a weighted average of intensity values from nearby pixels. This weight is based on a Gaussian distribution. The weights depend not only on Euclidean distance of pixels, but also on the radiometric differences (e.g., range differences, such as color intensity, depth distance, etc.). This preserves sharp edges. The default value for the intensity and spatial sigmas are 2*diameter and 0.5*diameter respectively. |
BlackThreshold |
threshold=>color, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | force all pixels below the threshold intensity into black |
BlueShift |
factor=>double | simulate a scene at nighttime in the moonlight. Start with a factor of 1.5. |
Blur |
geometry=>geometry, radius=>double, sigma=>double, bias=>double, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | reduce image noise and reduce detail levels with a Gaussian operator of the given radius and standard deviation (sigma). |
Border |
geometry=>geometry, width=>integer, height=>integer, bordercolor=>color name, compose=>{Undefined, Add, Atop, Blend, Bumpmap, Clear, ColorBurn, ColorDodge, Colorize, CopyBlack, CopyBlue, CopyCMYK, Cyan, CopyGreen, Copy, CopyMagenta, CopyAlpha, CopyRed, RGB, CopyYellow, Darken, Dst, Difference, Displace, Dissolve, DstAtop, DstIn, DstOut, DstOver, Dst, Exclusion, HardLight, Hue, In, Lighten, Luminize, Minus, Modulate, Multiply, None, Out, Overlay, Over, Plus, ReplaceCompositeOp, Saturate, Screen, SoftLight, Src, SrcAtop, SrcIn, SrcOut, SrcOver, Src, Subtract, Threshold, Xor } | surround the image with a border of color |
CannyEdge |
geometry=>geometry, radius=>double, sigma=>double, 'lower-percent'=>double, 'upper-percent'=>double | use a multi-stage algorithm to detect a wide range of edges in the image (e.g. CannyEdge('0x1+10%+40%')). |
Charcoal |
geometry=>geometry, radius=>double, sigma=>double | simulate a charcoal drawing |
Chop |
geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer, gravity=>{NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast} | chop an image |
CLAHE |
geometry=>geometry, width=>integer, height=>integer, number-bins=>integer, clip-limit=>double | contrast limited adaptive histogram equalization. width, height divides the image into tiles. number-bins is the number of histogram bins per tile (min 2, max 256). clip-limit is the contrast limit for localised changes in contrast. A clip-limit of 2 to 3 is a good starting place. |
Clamp |
channel=>{Red, RGB, All, etc.} | set each pixel whose value is below zero to zero and any pixel whose value is above the quantum range to the quantum range (e.g. 65535) otherwise the pixel value remains unchanged. |
Clip |
id=>name, inside=>{true, false} | apply along a named path from the 8BIM profile. |
ClipMask |
mask=>image-handle | clip image as defined by the image mask |
Clut |
image=>image-handle, interpolate={Average, Bicubic, Bilinear, Filter, Integer, Mesh, NearestNeighbor}, channel=>{Red, RGB, All, etc.} | apply a color lookup table to an image sequence |
Color |
color=>color name | set the entire image to this color. |
ColorDecisionList |
filename=>string | color correct with a color decision list. |
Colorize |
fill=>color name, blend=>string | colorize the image with the fill color |
ColorMatrix |
matrix=>array of float values | apply color correction to the image. Although you can use variable sized matrices, typically you use a 5 x 5 for an RGBA image and a 6x6 for CMYKA. A 6x6 matrix is required for offsets (populate the last column with normalized values). |
Colorspace |
colorspace=>{RGB, Gray, Transparent, OHTA, XYZ, YCbCr, YCC, YIQ, YPbPr, YUV, CMYK} | set the image colorspace |
Comment |
string | add a comment to your image |
ColorThreshold |
start-color=>color, stop-color=>color, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | force all pixels below the threshold intensity into black |
CompareLayers |
method=>{any, clear, overlay} | compares each image with the next in a sequence and returns the minimum bounding region of any pixel differences it discovers. Images do not have to be the same size, though it is best that all the images are coalesced (images are all the same size, on a flattened canvas, so as to represent exactly how a specific frame should look). |
Composite |
image=>image-handle, compose=>{Undefined, Add, Atop, Blend, Bumpmap, Clear, ColorBurn, ColorDodge, Colorize, CopyBlack, CopyBlue, CopyCMYK, Cyan, CopyGreen, Copy, CopyMagenta, CopyAlpha, CopyRed, RGB, CopyYellow, Darken, Dst, Difference, Displace, Dissolve, DstAtop, DstIn, DstOut, DstOver, Dst, Exclusion, HardLight, Hue, In, Lighten, Luminize, Minus, Modulate, Multiply, None, Out, Overlay, Over, Plus, ReplaceCompositeOp, Saturate, Screen, SoftLight, Src, SrcAtop, SrcIn, SrcOut, SrcOver, Src, Subtract, Threshold, Xor }, mask=>image-handle, geometry=>geometry, x=>integer, y=>integer, gravity=>{NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast}, opacity=>integer, tile=>{True, False}, rotate=>double, color=>color name, blend=>geometry, interpolate=>{undefined, average, bicubic, bilinear, filter, integer, mesh, nearest-neighbor, spline}, clip-to-self=>{True, False} | composite one image onto another. Use the rotate parameter in concert with the tile parameter. |
ConnectedComponents |
connectivity=>integer | connected-components uniquely labeled, choose from 4 or 8 way connectivity. |
Contrast |
sharpen=>{True, False} | enhance or reduce the image contrast |
ContrastStretch |
levels=>string, 'black-point'=>double, 'white-point'=>double, channel=>{Red, RGB, All, etc.} | improve the contrast in an image by `stretching' the range of intensity values |
Convolve |
coefficients=>array of float values, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow}, bias=>double | apply a convolution kernel to the image. Given a kernel order , you would supply order*order float values (e.g. 3x3 implies 9 values). |
CopyPixels |
image=>image-handle, geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer, offset=>geometry, gravity=>{NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast}, dx=>integer, dy=>integer | copy pixels from the image as defined by the widthxheight+x+y to image at offset +dx,+dy. |
Crop |
geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer, fuzz=>double, gravity=>{NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast} | crop an image |
CycleColormap |
amount=>integer | displace image colormap by amount |
Decipher |
passphrase=>string | convert cipher pixels to plain pixels |
Deconstruct |
- | break down an image sequence into constituent parts |
Deskew |
geometry=>string,threshold=>double | straighten the image |
Despeckle |
- | reduce the speckles within an image |
Difference |
image=>image-handle | compute the difference metrics between two images |
Distort |
points=>array of float values, method=>{Affine, AffineProjection, ScaleRotateTranslate, SRT, Perspective, PerspectiveProjection, BilinearForward, BilinearReverse, Polynomial, Arc, Polar, DePolar, Barrel, BarrelInverse, Shepards, Resize}, 'virtual-pixel'=>{Background Black Constant Dither Edge Gray Mirror Random Tile Transparent White}, 'best-fit'=>{True, False} | distort image |
Draw |
primitive=>{point, line, rectangle, arc, ellipse, circle, path, polyline, polygon, bezier, color, matte, text, @filename}, points=>string , method=>{Point, Replace, Floodfill, FillToBorder, Reset}, stroke=>color name, fill=>color name, font=>string, pointsize=>integer, strokewidth=>float, antialias=>{true, false}, bordercolor=>color name, x=>float, y=>float, dash-offset=>float, dash-pattern=>array of float values, affine=>array of float values, translate=>float, float, scale=>float, float, rotate=>float, skewX=>float, skewY=>float, interpolate=>{undefined, average, bicubic, bilinear, mesh, nearest-neighbor, spline}, kerning=>float, text=>string, vector-graphics=>string, interline-spacing=>double, interword-spacing=>double, direction=>{right-to-left, left-to-right}, word-break=>{normal, break-word} | annotate an image with one or more graphic primitives. |
Encipher |
passphrase=>string | convert plain pixels to cipher pixels |
Edge |
radius=>double | enhance edges within the image with a convolution filter of the given radius. |
Emboss |
geometry=>geometry, radius=>double, sigma=>double | emboss the image with a convolution filter of the given radius and standard deviation (sigma). |
Enhance |
- | apply a digital filter to enhance a noisy image |
Equalize |
channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | perform histogram equalization to the image |
Extent |
geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer, fuzz=>double, background=>color name, gravity=>{NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast} | set the image size |
Evaluate |
value=>double, operator=>{Add, And, Divide, LeftShift, Max, Min, Multiply, Or, Rightshift, RMS, Subtract, Xor}, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | apply an arithmetic, relational, or logical expression to the image |
Filter |
kernel=>string, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow}, bias=>double | apply a convolution kernel to the image. |
Flip |
- | reflect the image scanlines in the vertical direction |
Flop |
- | reflect the image scanlines in the horizontal direction |
FloodfillPaint |
geometry=>geometry, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow}, x=>integer, y=>integer , fill=>color name, bordercolor=>color name, fuzz=>double, invert=>{True, False} | changes the color value of any pixel that matches the color of the target pixel and is a neighbor. If you specify a border color, the color value is changed for any neighbor pixel that is not that color. |
ForwardFourierTransform |
magnitude=>{True, False} | implements the forward discrete Fourier transform (DFT) |
Frame |
geometry=>geometry, width=>integer, height=>integer, inner=>integer, outer=>integer, fill=>color name, compose=>{Undefined, Add, Atop, Blend, Bumpmap, Clear, ColorBurn, ColorDodge, Colorize, CopyBlack, CopyBlue, CopyCMYK, Cyan, CopyGreen, Copy, CopyMagenta, CopyAlpha, CopyRed, RGB, CopyYellow, Darken, Dst, Difference, Displace, Dissolve, DstAtop, DstIn, DstOut, DstOver, Dst, Exclusion, HardLight, Hue, In, Lighten, Luminize, Minus, Modulate, Multiply, None, Out, Overlay, Over, Plus, ReplaceCompositeOp, Saturate, Screen, SoftLight, Src, SrcAtop, SrcIn, SrcOut, SrcOver, Src, Subtract, Threshold, Xor } | surround the image with an ornamental border |
Function |
parameters=>array of float values, function=>{Sin}, 'virtual-pixel'=>{Background Black Constant Dither Edge Gray Mirror Random Tile Transparent White} | apply a function to the image |
Gamma |
gamma=>string, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | gamma correct the image |
GaussianBlur |
geometry=>geometry, radius=>double, sigma=>double, bias=>double, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | reduce image noise and reduce detail levels with a Gaussian operator of the given radius and standard deviation (sigma). |
GetPixel |
geometry=>geometry, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow}, normalize=>{true, false}, x=>integer, y=>integer | get a single pixel. By default normalized pixel values are returned. |
GetPixels |
geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer, map=>string, normalize=>{true, false} | get image pixels as defined by the map (e.g. "RGB", "RGBA", etc.). By default non-normalized pixel values are returned. |
Grayscale |
channel=>{Average, Brightness, Lightness, Rec601Luma, Rec601Luminance, Rec709Luma, Rec709Luminance, RMS} | convert image to grayscale |
HaldClut |
image=>image-handle, channel=>{Red, RGB, All, etc.} | apply a Hald color lookup table to an image sequence |
HoughLine |
geometry=>geometry, width=>double, height=>double, threshold=>double | identify lines in the image (e.g. HoughLine('9x9+195')). |
Identify |
file=>file, features=>distance, moments=>{True, False}, unique=>{True, False} | identify the attributes of an image |
Implode |
amount=>double, interpolate=>{undefined, average, bicubic, bilinear, mesh, nearest-neighbor, spline} | implode image pixels about the center |
Integral |
- | calculate the sum of values (pixel values) in the image. |
InverseDiscreteFourierTransform |
magnitude=>{True, False} | implements the inverse discrete Fourier transform (DFT) |
Kmeans |
geometry=>geometry, 'colors'=>double, 'iterations'=>double, 'tolerance'=>double | K means color reduction. |
Kuwahara |
geometry=>geometry, radius=>double, sigma=>double, bias=>double, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | edge preserving noise reduction filter |
Label |
string | assign a label to an image |
Layers |
method=>{coalesce, compare-any, compare-clear, compare-over, composite, dispose, flatten, merge, mosaic, optimize, optimize-image, optimize-plus, optimize-trans, remove-dups, remove-zero}, compose=>{Undefined, Add, Atop, Blend, Bumpmap, Clear, ColorBurn, ColorDodge, Colorize, CopyBlack, CopyBlue, CopyCMYK, Cyan, CopyGreen, Copy, CopyMagenta, CopyAlpha, CopyRed, RGB, CopyYellow, Darken, Dst, Difference, Displace, Dissolve, DstAtop, DstIn, DstOut, DstOver, Dst, Exclusion, HardLight, Hue, In, Lighten, LinearLight, Luminize, Minus, Modulate, Multiply, None, Out, Overlay, Over, Plus, ReplaceCompositeOp, Saturate, Screen, SoftLight, Src, SrcAtop, SrcIn, SrcOut, SrcOver, Src, Subtract, Threshold, Xor }, dither=>{true, false} | compare each image the GIF disposed forms of the previous image in the sequence. From this, attempt to select the smallest cropped image to replace each frame, while preserving the results of the animation. |
Level |
levels=>string, 'black-point'=>double, 'gamma'=>double, 'white-point'=>double, channel=>{Red, RGB, All, etc.} | adjust the level of image contrast |
LevelColors |
invert=>>{True, False}, 'black-point'=>string, 'white-point'=>string, channel=>{Red, RGB, All, etc.} | level image with the given colors |
LinearStretch |
levels=>string, 'black-point'=>double, 'white-point'=>double | linear with saturation stretch |
LiquidResize |
geometry=>geometry, width=>integer, height=>integer, delta-x=>double, rigidity=>double | rescale image with seam-carving. |
Magnify |
- | double the size of the image with pixel art scaling |
Mask |
mask=>image-handle | composite image pixels as defined by the mask |
MatteFloodfill |
geometry=>geometry, x=>integer, y=>integer , matte=>integer, bordercolor=>color name, fuzz=>double, invert=>{True, False} | changes the matte value of any pixel that matches the color of the target pixel and is a neighbor. If you specify a border color, the matte value is changed for any neighbor pixel that is not that color. |
MeanShift |
geometry=>geometry, width=>double, height=>double, distance=>double | delineate arbitrarily shaped clusters in the image (e.g. MeanShift('7x7+10%')). |
MedianFilter |
geometry=>geometry, width=>integer, height=>integer, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | replace each pixel with the median intensity pixel of a neighborhood. |
Minify |
- | half the size of an image |
Mode |
geometry=>geometry, width=>integer, height=>integer, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | make each pixel the predominant color of the neighborhood. |
Modulate |
factor=>geometry, brightness=>double, saturation=>double, hue=>double, lightness=>double, whiteness=>double, blackness=>double | vary the brightness, saturation, and hue of an image by the specified percentage |
Morphology |
kernel=>string, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow}, iterations=>integer | apply a morphology method to the image. |
MotionBlur |
geometry=>geometry, radius=>double, sigma=>double, angle=>double, bias=>double, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | reduce image noise and reduce detail levels with a Gaussian operator of the given radius and standard deviation (sigma) at the given angle to simulate the effect of motion |
Negate |
gray=>{True, False}, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | replace each pixel with its complementary color (white becomes black, yellow becomes blue, etc.) |
Normalize |
channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | transform image to span the full range of color values |
OilPaint |
radius=>integer | simulate an oil painting |
Opaque |
color=>color name, fill=>color name, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow}, invert=>{True, False} | change this color to the fill color within the image |
OrderedDither |
threshold=>{threshold, checks, o2x2, o3x3, o4x4, o8x8, h4x4a, h6x6a, h8x8a, h4x4o, h6x6o, h8x8o, h16x16o, hlines6x4}, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | order dither image |
Perceptible |
epsilon=>double, channel=>{Red, RGB, All, etc.} | set each pixel whose value is less than |epsilon| to -epsilon or epsilon (whichever is closer) otherwise the pixel value remains unchanged.. |
Polaroid |
caption=>string, angle=>double, pointsize=>double, font=>string, stroke=> color name, strokewidth=>integer, fill=>color name, gravity=>{NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast}, background=>color name | simulate a Polaroid picture. |
Posterize |
levels=>integer, dither=>{True, False} | reduce the image to a limited number of color level |
Profile |
name=>string, profile=>blob, rendering-intent=>{Undefined, Saturation, Perceptual, Absolute, Relative}, black-point-compensation=>{True, False} | add or remove ICC or IPTC image profile; name is formal name (e.g. ICC or filename; set profile to '' to remove profile |
Quantize |
colors=>integer, colorspace=>{RGB, Gray, Transparent, OHTA, XYZ, YCbCr, YIQ, YPbPr, YUV, CMYK, sRGB, HSL, HSB}, treedepth=> integer, dither=>{True, False}, dither-method=>{Riemersma, Floyd-Steinberg}, measure_error=>{True, False}, global_colormap=>{True, False}, transparent-color=>color | preferred number of colors in the image |
Raise |
geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer, raise=>{True, False} | lighten or darken image edges to create a 3-D effect |
RangeThreshold |
geometry=>geometry, 'low-black'=>double, 'low-white'=>double, 'high-white'=>double, 'high-black'=>double | combine soft and hard image thresholding. |
ReduceNoise |
geometry=>geometry, width=>integer, height=>integer, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | reduce noise in the image with a noise peak elimination filter |
Remap |
image=>image-handle, dither=>{true, false}, dither-method=>{Riemersma, Floyd-Steinberg} | replace the colors of an image with the closest color from a reference image. |
Resample |
density=>geometry, x=>double, y=>double, filter=>{Point, Box, Triangle, Hermite, Hanning, Hamming, Blackman, Gaussian, Quadratic, Cubic, Catrom, Mitchell, Lanczos, Bessel, Sinc}, support=>double | resample image to desired resolution. Specify blur > 1 for blurry or < 1 for sharp |
Resize |
geometry=>geometry, width=>integer, height=>integer, filter=>{Point, Box, Triangle, Hermite, Hanning, Hamming, Blackman, Gaussian, Quadratic, Cubic, Catrom, Mitchell, Lanczos, Bessel, Sinc}, support=>double, blur=>double | scale image to desired size. Specify blur > 1 for blurry or < 1 for sharp |
Roll |
geometry=>geometry, x=>integer, y=>integer | roll an image vertically or horizontally |
Rotate |
degrees=>double, background=>color name | rotate an image |
RotationalBlur |
geometry=>geometry, angle=>double, bias=>double, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | radial blur the image. |
Sample |
geometry=>geometry, width=>integer, height=>integer | scale image with pixel sampling. |
Scale |
geometry=>geometry, width=>integer, height=>integer | scale image to desired size |
Segment |
colorspace=>{RGB, Gray, Transparent, OHTA, XYZ, YCbCr, YCC, YIQ, YPbPr, YUV, CMYK}, verbose={True, False}, cluster-threshold=>double, smoothing-threshold=double | segment an image by analyzing the histograms of the color components and identifying units that are homogeneous |
SelectiveBlur |
geometry=>geometry, radius=>double, sigma=>double, threshold=>double, bias=>double, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | selectively blur pixels within a contrast threshold. |
Separate |
channel=>{Red, RGB, All, etc.} | separate a channel from the image into a grayscale image |
Shade |
geometry=>geometry, azimuth=>double, elevation=>double, gray=>{true, false} | shade the image using a distant light source |
SetPixel |
geometry=>geometry, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow}, color=>array of float values, x=>integer, y=>integer, color=>array of float values | set the value a single pixel. Normalized pixel values are expected. |
SetPixels |
geometry=>geometry, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow}, color=>array of float values, width=>integer, height=>integer, x=>integer, y=>integer, color=>array of float values | set the value of one or more pixels. Normalized pixel values are expected. |
Shadow |
geometry=>geometry, opacity=>double, sigma=>double, x=>integer, y=>integer | simulate an image shadow |
Sharpen |
geometry=>geometry, radius=>double, sigma=>double, bias=>double, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | sharpen the image with a Gaussian operator of the given radius and standard deviation (sigma). |
Shave |
geometry=>geometry, width=>integer, height=>integer | shave pixels from the image edges |
Shear |
geometry=>geometry, x=>double, y=>double fill=>color name | shear the image along the X or Y axis by a positive or negative shear angle |
SigmoidalContrast |
geometry=>string, 'contrast'=>double, 'mid-point'=>double channel=>{Red, RGB, All, etc.}, sharpen=>{True, False} | sigmoidal non-linearity contrast control. Increase the contrast of the image using a sigmoidal transfer function without saturating highlights or shadows. Contrast indicates how much to increase the contrast (0 is none; 3 is typical; 20 is a lot); mid-point indicates where midtones fall in the resultant image (0 is white; 50% is middle-gray; 100% is black). To decrease contrast, set sharpen to False. |
Signature |
- | generate an SHA-256 message digest for the image pixel stream |
Sketch |
geometry=>geometry, radius=>double, sigma=>double, angle=>double | sketch the image with a Gaussian operator of the given radius and standard deviation (sigma) at the given angle |
Solarize |
geometry=>string, threshold=>double, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | negate all pixels above the threshold level |
SortPixels |
- | sorts pixels within each scanline in ascending order of intensity. |
SparseColor |
points=>array of float values, method=>{Barycentric, Bilinear, Shepards, Voronoi}, 'virtual-pixel'=>{Background Black Constant Dither Edge Gray Mirror Random Tile Transparent White} | interpolate the image colors around the supplied points |
Splice |
geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer, fuzz=>double, background=>color name, gravity=>{NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast} | splice an image |
Spread |
radius=>double, interpolate=>{undefined, average, bicubic, bilinear, mesh, nearest-neighbor, spline} | displace image pixels by a random amount |
Statistic |
geometry=>geometry, width=>integer, height=>integer, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow}, type=>{Contrast, Median, Mode, Mean, Maximum, Minimum, ReduceNoise, RMS} | replace each pixel with corresponding statistic from the neighborhood. |
Stegano |
image=>image-handle, offset=>integer | hide a digital watermark within the image |
Stereo |
image=>image-handle, x=>integer, y=>integer | composites two images and produces a single image that is the composite of a left and right image of a stereo pair |
Strip |
- | strip an image of all profiles and comments. |
Swirl |
degrees=>double, interpolate=>{undefined, average, bicubic, bilinear, mesh, nearest-neighbor, spline} | swirl image pixels about the center |
Texture |
texture=>image-handle | name of texture to tile onto the image background |
Thumbnail |
geometry=>geometry, width=>integer, height=>integer | changes the size of an image to the given dimensions and removes any associated profiles. |
Threshold |
threshold=>string, channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | threshold the image |
Tint |
fill=>color name, blend=>string | tint the image with the fill color. |
Transparent |
color=>color name, invert=>{True, False} | make this color transparent within the image |
Transpose |
- | flip image in the vertical direction and rotate 90 degrees |
Transverse |
- | flop image in the horizontal direction and rotate 270 degrees |
Trim |
- | remove edges that are the background color from the image |
UnsharpMask |
geometry=>geometry, radius=>double, sigma=>double, gain=>double, threshold=>double | sharpen the image with the unsharp mask algorithm. |
Vignette |
geometry=>geometry, radius=>double, sigma=>double, x=>integer, y=>integer, background=>color name | offset the edges of the image in vignette style |
Wave |
geometry=>geometry, amplitude=>double, wavelength=>double, interpolate=>{undefined, average, bicubic, bilinear, mesh, nearest-neighbor, spline} | alter an image along a sine wave |
WaveDenoise |
geometry=>geometry, threshold=>double, threshold=>double | removes noise from the image using a wavelet transform |
WhiteBalance |
- | applies white balancing to an image according to a grayworld assumption in the LAB colorspace. |
WhiteThreshold |
threshold=>string, , channel=>{All, Default, Alpha, Black, Blue, CMYK, Cyan, Gray, Green, Index, Magenta, Alpha, Red, RGB, Yellow} | force all pixels above the threshold intensity into white |
Note that the geometry parameter is a shortcut for width and height (e.g., geometry=>'106x80' is equivalent to width=>106, height=>80).
You can specify @filename in both Annotate() and Draw() to read text or graphic primitive instructions from a file on disk. For example:
$image->Draw(fill=>'red', primitive=>'rectangle',
points=>'20,20 100,100 40,40 200,200 60,60 300,300');
is equivalent to:
$image->Draw(fill=>'red', primitive=>'@draw.txt');
where draw.txt contains:
rectangle 20, 20 100, 100
rectangle 40, 40 200, 200
rectangle 60, 60 300, 300
The text parameter for Annotate(), Comment(), Draw(), and Label() can embed image metadata using these special format escapes:
%b file size
%c comment
%d directory
%e filename extension
%f filename
%g page geometry
%h height
%i input filename
%k number of unique colors
%l label
%m magick
%n number of scenes
%o output filename
%p page number
%q quantum depth
%r image class and colorspace
%s scene number
%t top of filename
%u unique temporary filename
%w width
%x x resolution
%y y resolution
%z image depth
%C image compression type
%D image dispose method
%H page height
%Q image compression quality
%T image delay
%W page width
%X page x offset
%Y page y offset
%@ bounding box
%# signature
%% a percent sign
\n newline
\r carriage return
For example, text=>"%m:%f %wx%h" produces an annotation such as MIFF:bird.miff 512x480 for an image titled bird.miff with width 512 and height 480.
You can optionally append Image to any method name above (for example, TrimImage() is an alias for Trim()). Most of these methods correspond directly to options in magick; see its documentation for further details.
Set an Image Attribute
Use method Set() to set an image attribute. For example:
$image->Set(dither=>'True');
$image->[$x]->Set(delay=>3);
Where this document specifies {True, False}, you may pass case-insensitive strings ('True' / 'False') or integers (1 / 0). Calling Get() on a Boolean attribute always returns 1 or 0.
| Attribute | Values | Description |
|---|---|---|
adjoin |
{True, False} | join images into a single multi-image file |
alpha |
{On, Off, Opaque, Transparent, Copy, Extract, Set} | control of and special operations involving the alpha/matte channel |
antialias |
{True, False} | remove pixel aliasing |
area-limit |
integer | set pixel area resource limit. |
attenuate |
double | lessen (or intensify) when adding noise to an image. |
authenticate |
string | decrypt image with this password. |
background |
color name | image background color |
blue-primary |
x-value, y-value | chromaticity blue primary point (e.g. 0.15, 0.06) |
bordercolor |
color name | set the image border color |
clip-mask |
image | associate a clip mask with the image. |
colormap[i] |
color name | color name (e.g. red) or hex value (e.g. #ccc) at position i |
comment |
string | set the image comment |
compression |
{None, BZip, Fax, Group4, JPEG, JPEG2000, LosslessJPEG, LZW, RLE, Zip} | type of image compression |
debug |
{All, Annotate, Blob, Cache, Coder, Configure, Deprecate, Draw, Exception, Locale, None, Resource, Transform, X11} | display copious debugging information |
delay |
integer | this many 1/100ths of a second must expire before displaying the next image in a sequence |
density |
geometry | vertical and horizontal resolution in pixels of the image |
depth |
integer | image depth |
direction |
{Undefined, right-to-left, left-to-right | render text right-to-left or left-to-right |
disk-limit |
integer | set disk resource limit |
dispose |
{Undefined, None, Background, Previous} | layer disposal method |
dither |
{True, False} | apply error diffusion to the image |
display |
string | specifies the X server to contact |
extract |
geometry | extract area from image |
file |
filehandle | set the image filehandle |
filename |
string | set the image filename |
fill |
color | The fill color paints any areas inside the outline of drawn shape. |
font |
string | use this font when annotating the image with text |
fuzz |
integer | colors within this distance are considered equal |
gamma |
double | gamma level of the image |
gravity |
{Forget, NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast} | type of image gravity |
green-primary |
x-value, y-value | chromaticity green primary point (e.g. 0.3, 0.6) |
index[x, y] |
string | colormap index at position (x, y) |
interlace |
{None, Line, Plane, Partition, JPEG, GIF, PNG} | the type of interlacing scheme |
iterations |
integer | add Netscape loop extension to your GIF animation |
label |
string | set the image label |
loop |
integer | add Netscape loop extension to your GIF animation |
magick |
string | set the image format |
map-limit |
integer | set map resource limit |
mask |
image | associate a mask with the image. |
matte |
{True, False} | enable the image matte channel |
mattecolor |
color name | set the image matte color |
memory-limit |
integer | set memory resource limit |
monochrome |
{True, False} | transform the image to black and white |
option |
string | associate an option with an image format (e.g. option=>'ps:imagemask' |
orientation |
{TopLeft, TopRight, BottomRight, BottomLeft, LeftTop, RightTop, RightBottom, LeftBottom} | image orientation |
page |
{ Letter, Tabloid, Ledger, Legal, Statement, Executive, A3, A4, A5, B4, B5, Folio, Quarto, 10x14} or geometry | preferred size and location of an image canvas |
pixel[x, y] |
string | hex value (e.g. #ccc) at position (x, y) |
pointsize |
integer | pointsize of the Postscript or TrueType font |
precision |
integer | set the maximum number of significant digits to be printed |
quality |
integer | JPEG/MIFF/PNG compression level |
red-primary |
x-value, y-value | chromaticity red primary point (e.g. 0.64, 0.33) |
sampling-factor |
geometry | horizontal and vertical sampling factor |
scene |
integer | image scene number |
server |
string | specifies the X server to contact |
size |
string | width and height of a raw image |
stroke |
color | The stroke color paints along the outline of a shape. |
texture |
string | name of texture to tile onto the image background |
tile-offset |
geometry | image tile offset |
time-limit |
integer | set time resource limit in seconds |
title |
string | set the image title |
type |
{Bilevel, Grayscale, GrayscaleMatte, Palette, PaletteMatte, TrueColor, TrueColorMatte, ColorSeparation, ColorSeparationMatte} | image type |
units |
{ Undefined, PixelsPerInch, PixelsPerCentimeter} | units of image resolution |
verbose |
{True, False} | print detailed information about the image |
virtual-pixel |
{Background Black Constant Dither Edge Gray Mirror Random Tile Transparent White} | the virtual pixel method |
white-point |
x-value, y-value | chromaticity white point (e.g. 0.3127, 0.329) |
Note that the geometry parameter is a shortcut for width and height (e.g., geometry=>'106x80' is equivalent to width=>106, height=>80). SetAttribute() is an alias for Set(). Most attributes above correspond to options in magick.
Get an Image Attribute
Use method Get() to retrieve one or more image attributes. For example:
($a, $b, $c) = $image->Get('colorspace', 'magick', 'adjoin');
$width = $image->[3]->Get('columns');
In addition to all attributes listed in Set an Image Attribute, you can retrieve these read-only attributes:
| Attribute | Values | Description |
|---|---|---|
area |
integer | current area resource consumed |
base-columns |
integer | base image width (before transformations) |
base-filename |
string | base image filename (before transformations) |
base-rows |
integer | base image height (before transformations) |
class |
{Direct, Pseudo} | image class |
colors |
integer | number of unique colors in the image |
columns |
integer | image width |
copyright |
string | get PerlMagick's copyright |
directory |
string | tile names from within an image montage |
elapsed-time |
double | elapsed time in seconds since the image was created |
error |
double | the mean error per pixel computed with methods Compare() or Quantize() |
bounding-box |
string | image bounding box |
disk |
integer | current disk resource consumed |
filesize |
integer | number of bytes of the image on disk |
format |
string | get the descriptive image format |
geometry |
string | image geometry |
height |
integer | the number of rows or height of an image |
icc |
string | ICC profile |
icm |
string | ICM profile |
id |
integer | ImageMagick registry id |
IPTC |
string | IPTC profile |
mean-error |
double | the normalized mean error per pixel computed with methods Compare() or Quantize() |
map |
integer | current memory-mapped resource consumed |
matte |
{True, False} | whether or not the image has a matte channel |
maximum-error |
double | the normalized max error per pixel computed with methods Compare() or Quantize() |
memory |
integer | current memory resource consumed |
mime |
string | MIME of the image format |
montage |
geometry | tile size and offset within an image montage |
page.x |
integer | x offset of image virtual canvas |
page.y |
integer | y offset of image virtual canvas |
rows |
integer | the number of rows or height of an image |
signature |
string | SHA-256 message digest associated with the image pixel stream |
taint |
{True, False} | True if the image has been modified |
total-ink-density |
double | returns the total ink density for a CMYK image |
transparent-color |
color name | set the image transparent color |
user-time |
double | user time in seconds since the image was created |
version |
string | get PerlMagick's version |
width |
integer | the number of columns or width of an image |
XMP |
string | XMP profile |
x-resolution |
integer | x resolution of the image |
y-resolution |
integer | y resolution of the image |
GetAttribute() is an alias for Get(). Most attributes above correspond to options in magick.
Compare an Image to its Reconstruction
Mathematically and visually annotate the difference between an image and its reconstruction using the Compare() method:
| Parameter | Values | Description |
|---|---|---|
channel |
double | select image channels, the default is all channels except alpha. |
fuzz |
double | colors within this distance are considered equal |
image |
image-reference | the image reconstruction |
metric |
AE, MAE, MEPP, MSE, PAE, PSNR, RMSE | measure differences between images with this metric |
In this example, we compare the ImageMagick logo to a sharpened reconstruction:
use Image::Magick;
$logo = Image::Magick->New();
$logo->Read('logo:');
$sharp = Image::Magick->New();
$sharp->Read('logo:');
$sharp->Sharpen('0x1');
$difference = $logo->Compare(image=>$sharp, metric=>'rmse');
print $difference->Get('error'), "\n";
$difference->Display();
In addition to reporting a root mean squared error of around 0.024, a difference image is displayed to visually highlight variations between the two images.
Create an Image Montage
Use method Montage() to create a composite image by combining several separate images into tiled thumbnails, optionally labeled below each tile. For example:
$image->Montage(geometry=>'160x160', tile=>'2x2', texture=>'granite:');
| Parameter | Values | Description |
|---|---|---|
background |
color name | background color name |
border |
integer | image border width |
filename |
string | name of montage image |
fill |
color name | fill color for annotations |
font |
string | X11 font name |
frame |
geometry | surround the image with an ornamental border |
geometry |
geometry | preferred tile and border size of each tile of the composite image (e.g. 120x120+4+3>) |
gravity |
NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast | direction image gravitates to within a tile |
label |
string | assign a label to an image |
mode |
Frame, Unframe, Concatenate | thumbnail framing options |
pointsize |
integer | pointsize of the Postscript or TrueType font |
shadow |
{True, False} | add a shadow beneath a tile to simulate depth |
stroke |
color name | stroke color for annotations |
texture |
string | name of texture to tile onto the image background |
tile |
geometry | the number of tiles per row and page (e.g. 6x4) |
title |
string | assign a title to the image montage |
transparent |
string | make this color transparent within the image |
Note that the geometry parameter is a shortcut for width and height (e.g., geometry=>'106x80' is equivalent to width=>106, height=>80). MontageImage() is an alias for Montage(). Most attributes above correspond to options in montage.
Working with Blobs
A blob contains binary data representing an image directly in memory rather than on disk. PerlMagick supports blobs across all supported image formats and provides methods to convert between images and blobs:
| Method | Parameters | Return Value | Description |
|---|---|---|---|
ImageToBlob |
any image attribute | an array of image data in the respective image format | convert an image or image sequence to an array of blobs |
BlobToImage |
one or more blobs | the number of blobs converted to an image | convert one or more blobs to an image |
ImageToBlob() returns image data in its respective format, which you can print, store in an ODBC database, write to a file, or pipe to a display program:
@blobs = $image->ImageToBlob();
open(DISPLAY, "| display -") || die;
binmode DISPLAY;
print DISPLAY $blobs[0];
close DISPLAY;
BlobToImage() populates an image object from one or more supplied blobs:
@blob = $db->GetImage();
$image = Image::Magick->new(magick=>'jpg');
$image->BlobToImage(@blob);
Direct-access to Image Pixels
Use these methods to obtain direct low-level access to image pixels:
| Method | Parameters | Description |
|---|---|---|
GetAuthenticPixels |
geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer | return authentic pixels as a C pointer |
GetVirtualPixels |
geometry=>geometry, width=>integer, height=>integer, x=>integer, y=>integer | return virtual pixels as a const C pointer |
GetAuthenticIndexQueue |
- | return colormap indexes or black pixels as a C pointer |
GetVirtualIndexQueue |
- | return colormap indexes or black pixels as a const C pointer |
SyncAuthenticPixels |
- | sync authentic pixels to pixel cache |
Miscellaneous Methods
The Append() method joins a set of images left-to-right by default, or top-to-bottom when stack is set to True:
$p = $image->Append(stack=>{true,false});
The Clone() method copies all images from object $p to $q for single or multi-image sequences:
$q = $p->Clone();
Coalesce() composites an animation sequence (such as GIF, MIFF, or MNG) while respecting page offsets and disposal methods, returning a new sequence where every frame matches the virtual canvas size of the first image:
$q = $p->Coalesce();
The ComplexImages() method performs complex mathematics across an image sequence:
$p = $image->ComplexImages('conjugate');
The EvaluateImages() method applies an arithmetic, logical, or relational expression across a set of images (for example, averaging all frames):
$p = $image->EvaluateImages('mean');
The Features() method returns Haralick texture features for each channel in four directions (horizontal, vertical, and left/right diagonals) at the specified distance—including angular second momentum, contrast, correlation, variance, inverse difference moment, sum/difference averages, variances, entropies, and information measures of correlation—ordered as RGB, CMYK, RGBA, or CMYKA:
@features = $image->Features(1);
The Flatten() method composes each subsequent image in a sequence over the first image and returns a single flattened result:
$p = $images->Flatten(background=>'none');
$p->Write('flatten.png');
The Fx() method applies a mathematical expression to an image or sequence (for example, replacing the red channel with the average of green and blue). See FX, The Special Effects Image Operator for full syntax details:
$p = $image->Fx(expression=>'(g+b)/2.0', channel=>'red');
$p->Write('fx.miff');
Histogram() returns the unique colors in the image along with their pixel counts as an array of red, green, blue, opacity, and count values.
The Morph() method linearly interpolates both pixel values and dimensions between consecutive images to create a smooth metamorphosis (default is 1 in-between frame):
$p = $image->Morph(frames=>integer);
Mosaic() creates an image mosaic from an image sequence.
Mogrify() provides a single entry point for any method in Manipulate an Image, taking the method name followed by its parameters. These two calls are equivalent:
$image->Crop('340x256+0+0');
$image->Mogrify('crop', '340x256+0+0');
MogrifyRegion() works like Mogrify() but restricts the transformation to a specified geometry region (for example, brightening a 100×100 region at offset (40, 50)):
$image->MogrifyRegion('100x100+40+50', 'modulate', brightness=>50);
PerceptualHash() computes perceptual hashes that map visually identical images to identical or closely matching values—useful for image retrieval, authentication, indexing, copy detection, and watermarking. Seven hash values are returned per channel across both sRGB and HCLp colorspaces (42 values total for an sRGB image):
@phash = $image->PerceptualHash();
Ping() efficiently queries image metadata—returning width, height, file size in bytes, and format—without decoding the full image into memory. It accepts multiple filenames or a single filehandle or blob:
($width, $height, $size, $format) = $image->Ping('logo.png');
($width, $height, $size, $format) = $image->Ping(file=>\*IMAGE);
($width, $height, $size, $format) = $image->Ping(blob=>$blob);
Poly() builds a polynomial image from an image sequence using pairs of coefficient and degree terms:
$p = $image->Poly([0.5,1.0,0.25,2.0,1.0,1.0]);
PreviewImage() tiles 9 thumbnails of an image with a processing operation applied at varying strengths to help determine optimal parameters. Supported operations: Rotate, Shear, Roll, Hue, Saturation, Brightness, Gamma, Spiff, Dull, Grayscale, Quantize, Despeckle, ReduceNoise, AddNoise, Sharpen, Blur, Threshold, EdgeDetect, Spread, Solarize, Shade, Raise, Segment, Swirl, Implode, Wave, OilPaint, CharcoalDrawing, JPEG:
$preview = $image->Preview('Gamma');
$preview->Display();
QueryFontMetrics() accepts any Annotate parameter and returns 13 font metric values for precise text layout: (1) character width, (2) character height, (3) ascender, (4) descender, (5) text width, (6) text height, (7) maximum horizontal advance, (8–11) bounding box coordinates x1, y1, x2, y2, and (12–13) origin coordinates x, y:
($x_ppem, $y_ppem, $ascender, $descender, $width, $height, $max_advance) =
$image->QueryFontMetrics(parameters);
Use QueryMultilineFontMetrics() to obtain the maximum text width and height across multiple lines of text.
QueryColor() returns a list of all known color names when called without arguments, or returns red, green, blue, and opacity values for specified color names:
@colors = $image->QueryColor();
($red, $green, $blue) = $image->QueryColor('cyan');
($red, $green, $blue, $alpha) = $image->QueryColor('#716baeff');
QueryColorname() accepts a color specification and returns its corresponding color name or hex string:
$name = $image->QueryColorname('rgba(80,60,0,0)');
QueryFont() returns a list of all known fonts when called without arguments, or returns 11 font attributes (name, description, family, style, stretch, weight, encoding, foundry, format, metrics, and glyphs) for specified font names:
@fonts = $image->QueryFont();
$weight = ($image->QueryFont('Helvetica'))[5];
QueryFormat() returns a list of known image formats when called without arguments, or returns 7 format attributes (adjoin, blob support, raw, decoder, encoder, description, and module) for specified format names:
@formats = $image->QueryFormat();
($adjoin, $blob_support, $raw, $decoder, $encoder, $description, $module) =
$image->QueryFormat('gif');
MagickToMime() returns the MIME type (such as image/tiff) for a given image format name (such as tif):
$mime = $image->MagickToMime('tif');
RemoteCommand() sends a filename to an already running display or animate instance:
$image->RemoteCommand('image.jpg');
Shuffle() reorders the images in an image sequence using ascending, descending, or random criteria:
$image->Shuffle('random');
Smush() joins a set of images together without gaps (or with an optional pixel offset), stacking left-to-right by default or top-to-bottom when stack is True:
$p = $image->Smush(stack=>{true,false}, offset=>integer);
Statistics() returns channel statistics—depth, minima, maxima, mean, standard deviation, kurtosis, skewness, and entropy—in RGB, CMYK, RGBA, or CMYKA order depending on image type:
@statistics = $image->Statistics();
Transform() accepts a fully-qualified geometry specification to crop or resize one or more images:
$p = $image->Transform(crop=>'100x100+0+0');
You can optionally append Image to any method name above (for example, PingImage() is an alias for Ping()).
Handling Exceptions
All PerlMagick methods return an undefined value in string context upon success. When an issue occurs, an error string containing an embedded numeric status code is returned. Status codes below 400 are warnings (indicating partial completion), whereas codes 400 or greater are fatal errors. Check exceptions according to the method's return type:
Methods returning a count (e.g., Read(), Write()):
$x = $image->Read(...);
warn "$x" if "$x"; # print the error message
$x =~ /(\d+)/;
print $1; # print the error number
print 0+$x; # print the number of images read
Methods operating in-place on an image (e.g., Resize(), Crop()):
$x = $image->Crop(...);
warn "$x" if "$x"; # print the error message
$x =~ /(\d+)/;
print $1; # print the error number
Methods returning a new image object (e.g., EvaluateSequence(), Montage(), Clone()):
$x = $image->Montage(...);
warn "$x" if !ref($x); # print the error message
$x =~ /(\d+)/;
print $1; # print the error number
An example error message looks like:
Error 400: Memory allocation failed
You can compare extracted numeric codes directly against PerlMagick exception constants (see the complete list of error and warning codes):
$x = $image->Read('rose.png');
$x =~ /(\d+)/;
die "unable to continue" if ($1 == ResourceLimitError);
Constants
PerlMagick defines the following constants:
BlobError
BlobWarning
CacheError
CacheWarning
CoderError
CoderWarning
ConfigureError
ConfigureWarning
CorruptImageError
CorruptImageWarning
DelegateError
DelegateWarning
DrawError
DrawWarning
ErrorException
FatalErrorException
FileOpenError
FileOpenWarning
ImageError
ImageWarning
MissingDelegateError
MissingDelegateWarning
ModuleError
ModuleWarning
Opaque
OptionError
OptionWarning
QuantumDepth
QuantumRange
RegistryError
RegistryWarning
ResourceLimitError
ResourceLimitWarning
StreamError
StreamWarning
Success
Transparent
TypeError
TypeWarning
WarningException
XServerError
XServerWarning
Access constants via the Image::Magick package, for example:
Image::Magick->QuantumDepth