Imager - Perl extension for Generating 24 bit Images use Imager qw(init); init(); $img = Imager->new(); $img->open(file=>'image.ppm',type=>'pnm') || print "failed: ",$img->{ERRSTR},"\n"; $scaled=$img->scale(xpixels=>400,ypixels=>400); $scaled->write(file=>'sc_image.ppm',type=>'pnm') || print "failed: ",$scaled->{ERRSTR},"\n"; Imager is a module for creating and altering images - It is not meant as a replacement or a competitor to ImageMagick or GD. Both are excellent packages and well supported.

API
Almost all functions take the parameters in the hash fashion. Example: $img->open(file=>'lena.png',type=>'png'); or just: $img->open(file=>'lena.png');

Basic concept
An Image object is created with `$img = Imager->new()' Should this fail for some reason an explanation can be found in `$Imager::ERRSTR' usually error messages are stored in `$img->{ERRSTR}', but since no object is created this is the only way to give back errors. `$Imager::ERRSTR' is also used to report all errors not directly associated with an image object. Examples: $img=Imager->new(); # This is an empty image (size is 0 by 0) $img->open(file=>'lena.png',type=>'png'); # initializes from file or if you want to create an empty image: $img=Imager->new(xsize=>400,ysize=>300,channels=>4); This example creates a completely black image of width 400 and height 300 and 4 channels. If you have an existing image, use img_set() to change it's dimensions - this will destroy any existing image data: $img->img_set(xsize=>500, ysize=>500, channels=>4); To create paletted images, set the 'type' parameter to 'paletted': $img = Imager->new(xsize=>200, ysize=>200, channels=>3, type=>'paletted'); which creates an image with a maxiumum of 256 colors, which you can change by supplying the `maxcolors' parameter. You can create a new paletted image from an existing image using the to_paletted() method: $palimg = $img->to_paletted(\%opts) where %opts contains the options specified under the Quantization options entry elsewhere in this document. You can convert a paletted image (or any image) to an 8-bit/channel RGB image with: $rgbimg = $img->to_rgb8; Warning: if you draw on a paletted image with colors that aren't in the palette, the image will be internally converted to a normal image. For improved color precision you can use the bits parameter to specify 16 bit per channel: $img = Imager->new(xsize=>200, ysize=>200, channels=>3, bits=>16); or for even more precision: $img = Imager->new(xsize=>200, ysize=>200, channels=>3, bits=>'double'); to get an image that uses a double for each channel. Note that as of this writing all functions should work on images with more than 8-bits/channel, but many will only work at only 8-bit/channel precision. Currently only 8-bit, 16-bit, and double per channel image types are available, this may change later. Color objects are created by calling the Imager::Color->new() method: $color = Imager::Color->new($red, $green, $blue); $color = Imager::Color->new($red, $green, $blue, $alpha); $color = Imager::Color->new("#C0C0FF"); # html color specification This object can then be passed to functions that require a color parameter. Coordinates in Imager have the origin in the upper left corner. The horizontal coordinate increases to the right and the vertical downwards.

Reading and writing images
`$img->read()' generally takes two parameters, 'file' and 'type'. If the type of the file can be determined from the suffix of the file it can be omitted. Format dependant parameters are: For images of type 'raw' two extra parameters are needed 'xsize' and 'ysize', if the 'channel' parameter is omitted for type 'raw' it is assumed to be 3. gif and png images might have a palette are converted to truecolor bit when read. Alpha channel is preserved for png images irregardless of them being in RGB or gray colorspace. Similarly grayscale jpegs are one channel images after reading them. For jpeg images the iptc header information (stored in the APP13 header) is avaliable to some degree. You can get the raw header with `$img->{IPTCRAW}', but you can also retrieve the most basic information with `%hsh=$img->parseiptc()' as always patches are welcome. pnm has no extra options. Examples: $img = Imager->new(); $img->read(file=>"cover.jpg") or die $img->errstr; # gets type from name $img = Imager->new(); { local(*FH,$/); open(FH,"file.gif") or die $!; $a=<FH>; } $img->read(data=>$a,type=>'gif') or die $img->errstr; The second example shows how to read an image from a scalar, this is usefull if your data originates from somewhere else than a filesystem such as a database over a DBI connection. When writing to a tiff image file you can also specify the 'class' parameter, which can currently take a single value, "fax". If class is set to fax then a tiff image which should be suitable for faxing will be written. For the best results start with a grayscale image. By default the image is written at fine resolution you can override this by setting the "fax_fine" parameter to 0. If you are reading from a gif image file, you can supply a 'colors' parameter which must be a reference to a scalar. The referenced scalar will receive an array reference which contains the colors, each represented as an Imager::Color object. If you already have an open file handle, for example a socket or a pipe, you can specify the 'fd' parameter instead of supplying a filename. Please be aware that you need to use fileno() to retrieve the file descriptor for the file: $img->read(fd=>fileno(FILE), type=>'gif') or die $img->errstr; For writing using the 'fd' option you will probably want to set $| for that descriptor, since the writes to the file descriptor bypass Perl's (or the C libraries) buffering. Setting $| should avoid out of order output. For example a common idiom when writing a CGI script is: # the $| _must_ come before you send the content-type $| = 1; print "Content-Type: image/jpeg\n\n"; $img->write(fd=>fileno(STDOUT), type=>'jpeg') or die $img->errstr; *Note that load() is now an alias for read but will be removed later* `$img->write' has the same interface as `read()'. The earlier comments on `read()' for autodetecting filetypes apply. For jpegs quality can be adjusted via the 'jpegquality' parameter (0-100). The number of colorplanes in gifs are set with 'gifplanes' and should be between 1 (2 color) and 8 (256 colors). It is also possible to choose between two quantizing methods with the parameter 'gifquant'. If set to mc it uses the mediancut algorithm from either giflibrary. If set to lm it uses a local means algorithm. It is then possible to give some extra settings. lmdither is the dither deviation amount in pixels (manhattan distance). lmfixed can be an array ref who holds an array of Imager::Color objects. Note that the local means algorithm needs much more cpu time but also gives considerable better results than the median cut algorithm. When storing targa images rle compression can be activated with the 'compress' parameter, the 'idstring' parameter can be used to set the targa comment field and the 'wierdpack' option can be used to use the 15 and 16 bit targa formats for rgb and rgba data. The 15 bit format has 5 of each red, green and blue. The 16 bit format in addition allows 1 bit of alpha. The most significant bits are used for each channel. Currently just for gif files, you can specify various options for the conversion from Imager's internal RGB format to the target's indexed file format. If you set the gifquant option to 'gen', you can use the options specified under the Quantization options entry elsewhere in this document. To see what Imager is compiled to support the following code snippet is sufficient: use Imager; print "@{[keys %Imager::formats]}"; When reading raw images you need to supply the width and height of the image in the xsize and ysize options: $img->read(file=>'foo.raw', xsize=>100, ysize=>100) or die "Cannot read raw image\n"; If your input file has more channels than you want, or (as is common), junk in the fourth channel, you can use the datachannels and storechannels options to control the number of channels in your input file and the resulting channels in your image. For example, if your input image uses 32-bits per pixel with red, green, blue and junk values for each pixel you could do: $img->read(file=>'foo.raw', xsize=>100, ysize=>100, datachannels=>4, storechannels=>3) or die "Cannot read raw image\n"; Normally the raw image is expected to have the value for channel 1 immediately following channel 0 and channel 2 immediately following channel 1 for each pixel. If your input image has all the channel 0 values for the first line of the image, followed by all the channel 1 values for the first line and so on, you can use the interleave option: $img->read(file=>'foo.raw', xsize=100, ysize=>100, interleave=>1) or die "Cannot read raw image\n";

Multi-image files
Currently just for gif files, you can create files that contain more than one image. To do this: Imager->write_multi(\%opts, @images) Where %opts describes 4 possible types of outputs: This is `gif' for gif animations. A code reference which is called with a single parameter, the data to be written. You can also specify $opts{maxbuffer} which is the maximum amount of data buffered. Note that there can be larger writes than this if the file library writes larger blocks. A smaller value maybe useful for writing to a socket for incremental display. The file descriptor to save the images to. The name of the file to write to. %opts may also include the keys from the Gif options entry elsewhere in this document and the Quantization options entry elsewhere in this document. You must also specify the file format using the 'type' option. The current aim is to support other multiple image formats in the future, such as TIFF, and to support reading multiple images from a single file. A simple example: my @images; # ... code to put images in @images Imager->write_multi({type=>'gif', file=>'anim.gif', gif_delays=>[ (10) x @images ] }, @images) or die "Oh dear!"; You can read multi-image files (currently only GIF files) using the read_multi() method: my @imgs = Imager->read_multi(file=>'foo.gif') or die "Cannot read images: ",Imager->errstr; The possible parameters for read_multi() are: The name of the file to read in. A filehandle to read in. This can be the name of a filehandle, but it will need the package name, no attempt is currently made to adjust this to the caller's package. The numeric file descriptor of an open file (or socket). A function to be called to read in data, eg. reading a blob from a database incrementally. The data of the input file in memory. The type of file. If the file is parameter is given and provides enough information to guess the type, then this parameter is optional. Note: you cannot use the callback or data parameter with giflib versions before 4.0. When reading from a GIF file with read_multi() the images are returned as paletted images.

Gif options
These options can be specified when calling write_multi() for gif files, when writing a single image with the gifquant option set to 'gen', or for direct calls to i_writegif_gen and i_writegif_callback. Note that some viewers will ignore some of these options (gif_user_input in particular). Each image in the gif file has it's own palette if this is non-zero. All but the first image has a local colour table (the first uses the global colour table. The images are written interlaced if this is non-zero. A reference to an array containing the delays between images, in 1/100 seconds. If you want the same delay for every frame you can simply set this to the delay in 1/100 seconds. A reference to an array contains user input flags. If the given flag is non-zero the image viewer should wait for input before displaying the next image. A reference to an array of image disposal methods. These define what should be done to the image before displaying the next one. These are integers, where 0 means unspecified, 1 means the image should be left in place, 2 means restore to background colour and 3 means restore to the previous value. A reference to an Imager::Color object, which is the colour to use for the palette entry used to represent transparency in the palette. You need to set the transp option (see the Quantization options entry elsewhere in this document) for this value to be used. A reference to an array of references to arrays which represent screen positions for each image. If this is non-zero the Netscape loop extension block is generated, which makes the animation of the images repeat. This is currently unimplemented due to some limitations in giflib. If this is true, when you write a paletted image any unused colors will be eliminated from its palette. This is set by default.

Quantization options
These options can be specified when calling write_multi() for gif files, when writing a single image with the gifquant option set to 'gen', or for direct calls to i_writegif_gen and i_writegif_callback. A arrayref of colors that are fixed. Note that some color generators will ignore this. The type of transparency processing to perform for images with an alpha channel where the output format does not have a proper alpha channel (eg. gif). This can be any of: No transparency processing is done. (default) Pixels more transparent that tr_threshold are rendered as transparent. An error diffusion dither is done on the alpha channel. Note that this is independent of the translation performed on the colour channels, so some combinations may cause undesired artifacts. The ordered dither specified by tr_orddith is performed on the alpha channel. This will only be used if the image has an alpha channel, and if there is space in the palette for a transparency colour. The highest alpha value at which a pixel will be made transparent when transp is 'threshold'. (0-255, default 127) The type of error diffusion to perform on the alpha channel when transp is 'errdiff'. This can be any defined error diffusion type except for custom (see errdiff below). The type of ordered dither to perform on the alpha channel when transp is 'ordered'. Possible values are: A semi-random map is used. The map is the same each time. 8x8 dot dither. 4x4 dot dither horizontal line dither. vertical line dither. diagonal line dither diagonal line dither dot matrix dither (currently the default). This is probably the best for displays (like web pages). A custom dither matrix is used - see tr_map When tr_orddith is custom this defines an 8 x 8 matrix of integers representing the transparency threshold for pixels corresponding to each position. This should be a 64 element array where the first 8 entries correspond to the first row of the matrix. Values should be betweern 0 and 255. Defines how the quantization engine will build the palette(s). Currently this is ignored if 'translate' is 'giflib', but that may change. Possible values are: Only colors supplied in 'colors' are used. The web color map is used (need url here.) The original code for generating the color map (Addi's code) is used. Other methods may be added in the future. A arrayref containing Imager::Color objects, which represents the starting set of colors to use in translating the images. webmap will ignore this. The final colors used are copied back into this array (which is expanded if necessary.) The maximum number of colors to use in the image. The method used to translate the RGB values in the source image into the colors selected by make_colors. Note that make_colors is ignored whene translate is 'giflib'. Possible values are: The giflib native quantization function is used. The closest color available is used. The pixel color is modified by perturb, and the closest color is chosen. An error diffusion dither is performed. It's possible other transate values will be added. The type of error diffusion dither to perform. These values (except for custom) can also be used in tr_errdif. Floyd-Steinberg dither Jarvis, Judice and Ninke dither Stucki dither Custom. If you use this you must also set errdiff_width, errdiff_height and errdiff_map. When translate is 'errdiff' and errdiff is 'custom' these define a custom error diffusion map. errdiff_width and errdiff_height define the size of the map in the arrayref in errdiff_map. errdiff_orig is an integer which indicates the current pixel position in the top row of the map. When translate is 'perturb' this is the magnitude of the random bias applied to each channel of the pixel before it is looked up in the color table.

Obtaining/setting attributes of images
To get the size of an image in pixels the `$img->getwidth()' and `$img->getheight()' are used. To get the number of channels in an image `$img->getchannels()' is used. $img->getmask() and $img->setmask() are used to get/set the channel mask of the image. $mask=$img->getmask(); $img->setmask(mask=>1+2); # modify red and green only $img->setmask(mask=>8); # modify alpha only $img->setmask(mask=>$mask); # restore previous mask The mask of an image describes which channels are updated when some operation is performed on an image. Naturally it is not possible to apply masks to operations like scaling that alter the dimensions of images. It is possible to have Imager find the number of colors in an image by using `$img->getcolorcount()'. It requires memory proportionally to the number of colors in the image so it is possible to have it stop sooner if you only need to know if there are more than a certain number of colors in the image. If there are more colors than asked for the function return undef. Examples: if (!defined($img->getcolorcount(maxcolors=>512)) { print "Less than 512 colors in image\n"; } The bits() method retrieves the number of bits used to represent each channel in a pixel, 8 for a normal image, 16 for 16-bit image and 'double' for a double/channel image. The type() method returns either 'direct' for truecolor images or 'paletted' for paletted images. The virtual() method returns non-zero if the image contains no actual pixels, for example masked images.

Paletted Images
In general you can work with paletted images in the same way as RGB images, except that if you attempt to draw to a paletted image with a color that is not in the image's palette, the image will be converted to an RGB image. This means that drawing on a paletted image with anti-aliasing enabled will almost certainly convert the image to RGB. You can add colors to a paletted image with the addcolors() method: my @colors = ( Imager::Color->new(255, 0, 0), Imager::Color->new(0, 255, 0) ); my $index = $img->addcolors(colors=>\@colors); The return value is the index of the first color added, or undef if adding the colors would overflow the palette. Once you have colors in the palette you can overwrite them with the setcolors() method: $img->setcolors(start=>$start, colors=>\@colors); Returns true on success. To retrieve existing colors from the palette use the getcolors() method: # get the whole palette my @colors = $img->getcolors(); # get a single color my $color = $img->getcolors(start=>$index); # get a range of colors my @colors = $img->getcolors(start=>$index, count=>$count); To quickly find a color in the palette use findcolor(): my $index = $img->findcolor(color=>$color); which returns undef on failure, or the index of the color. You can get the current palette size with $img->colorcount, and the maximum size of the palette with $img->maxcolors.

Drawing Methods
IMPLEMENTATION MORE OR LESS DONE CHECK THE TESTS DOCUMENTATION OF THIS SECTION OUT OF SYNC It is possible to draw with graphics primitives onto images. Such primitives include boxes, arcs, circles and lines. A reference oriented list follows. Box: $img->box(color=>$blue,xmin=>10,ymin=>30,xmax=>200,ymax=>300,filled=>1); The above example calls the `box' method for the image and the box covers the pixels with in the rectangle specified. If `filled' is ommited it is drawn as an outline. If any of the edges of the box are ommited it will snap to the outer edge of the image in that direction. Also if a color is omitted a color with (255,255,255,255) is used instead. Arc: $img->arc(color=>$red, r=20, x=>200, y=>100, d1=>10, d2=>20 ); This creates a filled red arc with a 'center' at (200, 100) and spans 10 degrees and the slice has a radius of 20. SEE section on BUGS. Both the arc() and box() methods can take a `fill' parameter which can either be an Imager::Fill object, or a reference to a hash containing the parameters used to create the fill: $img->box(xmin=>10, ymin=>30, xmax=>150, ymax=>60, fill => { hatch=>'cross2' }); use Imager::Fill; my $fill = Imager::Fill->new(hatch=>'stipple'); $img->box(fill=>$fill); See the Imager::Fill manpage for the type of fills you can use. Circle: $img->circle(color=>$green, r=50, x=>200, y=>100); This creates a green circle with its center at (200, 100) and has a radius of 20. Line: $img->line(color=>$green, x1=10, x2=>100, y1=>20, y2=>50, antialias=>1 ); That draws an antialiased line from (10,100) to (20,50). Polyline: $img->polyline(points=>[[$x0,$y0],[$x1,$y1],[$x2,$y2]],color=>$red); $img->polyline(x=>[$x0,$x1,$x2], y=>[$y0,$y1,$y2], antialias=>1); Polyline is used to draw multilple lines between a series of points. The point set can either be specified as an arrayref to an array of array references (where each such array represents a point). The other way is to specify two array references. You can fill a region that all has the same color using the flood_fill() method, for example: $img->flood_fill(x=>50, y=>50, color=>$color); will fill all regions the same color connected to the point (50, 50). You can also use a general fill, so you could fill the same region with a check pattern using: $img->flood_fill(x=>50, y=>50, fill=>{ hatch=>'check2x2' }); See the Imager::Fill manpage for more information on general fills.

Text rendering
Text rendering is described in the Imager::Font manpage.

Image resizing
To scale an image so porportions are maintained use the `$img->scale()' method. if you give either a xpixels or ypixels parameter they will determine the width or height respectively. If both are given the one resulting in a larger image is used. example: `$img' is 700 pixels wide and 500 pixels tall. $img->scale(xpixels=>400); # 400x285 $img->scale(ypixels=>400); # 560x400 $img->scale(xpixels=>400,ypixels=>400); # 560x400 $img->scale(xpixels=>400,ypixels=>400,type=>min); # 400x285 $img->scale(scalefactor=>0.25); 175x125 $img->scale(); # 350x250 if you want to create low quality previews of images you can pass `qtype=>'preview'' to scale and it will use nearest neighbor sampling instead of filtering. It is much faster but also generates worse looking images - especially if the original has a lot of sharp variations and the scaled image is by more than 3-5 times smaller than the original. If you need to scale images per axis it is best to do it simply by calling scaleX and scaleY. You can pass either 'scalefactor' or 'pixels' to both functions. Another way to resize an image size is to crop it. The parameters to crop are the edges of the area that you want in the returned image. If a parameter is omited a default is used instead. $newimg = $img->crop(left=>50, right=>100, top=>10, bottom=>100); $newimg = $img->crop(left=>50, top=>10, width=>50, height=>90); $newimg = $img->crop(left=>50, right=>100); # top You can also specify width and height parameters which will produce a new image cropped from the center of the input image, with the given width and height. $newimg = $img->crop(width=>50, height=>50); The width and height parameters take precedence over the left/right and top/bottom parameters respectively.

Copying images
To create a copy of an image use the `copy()' method. This is usefull if you want to keep an original after doing something that changes the image inplace like writing text. $img=$orig->copy(); To copy an image to onto another image use the `paste()' method. $dest->paste(left=>40,top=>20,img=>$logo); That copies the entire `$logo' image onto the `$dest' image so that the upper left corner of the `$logo' image is at (40,20).

Flipping images
An inplace horizontal or vertical flip is possible by calling the `flip()' method. If the original is to be preserved it's possible to make a copy first. The only parameter it takes is the `dir' parameter which can take the values `h', `v', `vh' and `hv'. $img->flip(dir=>"h"); # horizontal flip $img->flip(dir=>"vh"); # vertical and horizontal flip $nimg = $img->copy->flip(dir=>"v"); # make a copy and flip it vertically

Rotating images
Use the rotate() method to rotate an image. This method will return a new, rotated image. To rotate by an exact amount in degrees or radians, use the 'degrees' or 'radians' parameter: my $rot20 = $img->rotate(degrees=>20); my $rotpi4 = $img->rotate(radians=>3.14159265/4); Exact image rotation uses the same underlying transformation engine as the matrix_transform() method. To rotate in steps of 90 degrees, use the 'right' parameter: my $rotated = $img->rotate(right=>270); Rotations are clockwise for positive values.

Blending Images
To put an image or a part of an image directly into another it is best to call the `paste()' method on the image you want to add to. $img->paste(img=>$srcimage,left=>30,top=>50); That will take paste `$srcimage' into `$img' with the upper left corner at (30,50). If no values are given for `left' or `top' they will default to 0. A more complicated way of blending images is where one image is put 'over' the other with a certain amount of opaqueness. The method that does this is rubthrough. $img->rubthrough(src=>$srcimage,tx=>30,ty=>50); That will take the image `$srcimage' and overlay it with the upper left corner at (30,50). You can rub 2 or 4 channel images onto a 3 channel image, or a 2 channel image onto a 1 channel image. The last channel is used as an alpha channel.

Filters
A special image method is the filter method. An example is: $img->filter(type=>'autolevels'); This will call the autolevels filter. Here is a list of the filters that are always avaliable in Imager. This list can be obtained by running the `filterlist.perl' script that comes with the module source. Filter Arguments autolevels lsat(0.1) usat(0.1) skew(0) bumpmap bump elevation(0) lightx lighty st(2) bumpmap_complex bump channel(0) tx(0) ty(0) Lx(0.2) Ly(0.4) Lz(-1) cd(1.0) cs(40.0) n(1.3) Ia(0 0 0) Il(255 255 255) Is(255 255 255) contrast intensity conv coef fountain xa ya xb yb ftype(linear) repeat(none) combine(none) super_sample(none) ssample_param(4) segments(see below) gaussian stddev gradgen xo yo colors dist hardinvert mosaic size(20) noise amount(3) subtype(0) postlevels levels(10) radnoise xo(100) yo(100) ascale(17.0) rscale(0.02) turbnoise xo(0.0) yo(0.0) scale(10.0) unsharpmask stddev(2.0) scale(1.0) watermark wmark pixdiff(10) tx(0) ty(0) The default values are in parenthesis. All parameters must have some value but if a parameter has a default value it may be omitted when calling the filter function. The filters are: scales the value of each channel so that the values in the image will cover the whole possible range for the channel. lsat and usat truncate the range by the specified fraction at the top and bottom of the range respectivly.. uses the channel elevation image bump as a bumpmap on your image, with the light at (lightx, lightty), with a shadow length of st. uses the channel channel image bump as a bumpmap on your image. If Lz<0 the three L parameters are considered to be the direction of the light. If Lz>0 the L parameters are considered to be the light position. Ia is the ambient colour, Il is the light colour, Is is the color of specular highlights. cd is the diffuse coefficient and cs is the specular coefficient. n is the shininess of the surface. scales each channel by intensity. Values of intensity < 1.0 will reduce the contrast. performs 2 1-dimensional convolutions on the image using the values from coef. coef should be have an odd length. renders a fountain fill, similar to the gradient tool in most paint software. The default fill is a linear fill from opaque black to opaque white. The points A(xa, ya) and B(xb, yb) control the way the fill is performed, depending on the ftype parameter: the fill ramps from A through to B. the fill ramps in both directions from A, where AB defines the length of the gradient. A is the center of a circle, and B is a point on it's circumference. The fill ramps from the center out to the circumference. A is the center of a square and B is the center of one of it's sides. This can be used to rotate the square. The fill ramps out to the edges of the square. A is the centre of a circle and B is a point on it's circumference. B marks the 0 and 360 point on the circle, with the fill ramping clockwise. A is the center of a circle and B is a point on it's circumference. B marks the 0 and point on the circle, with the fill ramping in both directions to meet opposite. The repeat option controls how the fill is repeated for some ftypes after it leaves the AB range: no repeats, points outside of each range are treated as if they were on the extreme end of that range. the fill simply repeats in the positive direction the fill repeats in reverse and then forward and so on, in the positive direction the fill repeats in both the positive and negative directions (only meaningful for a linear fill). as for triangle, but in the negative direction too (only meaningful for a linear fill). By default the fill simply overwrites the whole image (unless you have parts of the range 0 through 1 that aren't covered by a segment), if any segments of your fill have any transparency, you can set the combine option to 'normal' to have the fill combined with the existing pixels. See the description of combine in the Fill entry in the Imager manpage. If your fill has sharp edges, for example between steps if you use repeat set to 'triangle', you may see some aliased or ragged edges. You can enable super-sampling which will take extra samples within the pixel in an attempt anti-alias the fill. The possible values for the super_sample option are: no super-sampling is done a square grid of points are sampled. The number of points sampled is the square of ceil(0.5 + sqrt(ssample_param)). a random set of points within the pixel are sampled. This looks pretty bad for low ssample_param values. the points on the radius of a circle within the pixel are sampled. This seems to produce the best results, but is fairly slow (for now). You can control the level of sampling by setting the ssample_param option. This is roughly the number of points sampled, but depends on the type of sampling. The segments option is an arrayref of segments. You really should use the Imager::Fountain class to build your fountain fill. Each segment is an array ref containing: a floating point number between 0 and 1, the start of the range of fill parameters covered by this segment. a floating point number between start and end which can be used to push the color range towards one end of the segment. a floating point number between 0 and 1, the end of the range of fill parameters covered by this segment. This should be greater than start. The colors at each end of the segment. These can be either Imager::Color or Imager::Color::Float objects. The type of segment, this controls the way the fill parameter varies over the segment. 0 for linear, 1 for curved (unimplemented), 2 for sine, 3 for sphere increasing, 4 for sphere decreasing. The way the color varies within the segment, 0 for simple RGB, 1 for hue increasing and 2 for hue decreasing. Don't forgot to use Imager::Fountain instead of building your own. Really. It even loads GIMP gradient files. performs a gaussian blur of the image, using stddev as the standard deviation of the curve used to combine pixels, larger values give bigger blurs. For a definition of Gaussian Blur, see: http://www.maths.abdn.ac.uk/~igc/tch/mx4002/notes/node99.html renders a gradient, with the given colors at the corresponding points (x,y) in xo and yo. You can specify the way distance is measured for color blendeing by setting dist to 0 for Euclidean, 1 for Euclidean squared, and 2 for Manhattan distance. inverts the image, black to white, white to black. All channels are inverted, including the alpha channel if any. produces averaged tiles of the given size. adds noise of the given amount to the image. If subtype is zero, the noise is even to each channel, otherwise noise is added to each channel independently. renders radiant Perlin turbulent noise. The centre of the noise is at (xo, yo), ascale controls the angular scale of the noise , and rscale the radial scale, higher numbers give more detail. alters the image to have only levels distinct level in each channel. renders Perlin turbulent noise. (xo, yo) controls the origin of the noise, and scale the scale of the noise, with lower numbers giving more detail. performs an unsharp mask on the image. This is the result of subtracting a gaussian blurred version of the image from the original. stddev controls the stddev parameter of the gaussian blur. Each output pixel is: in + scale * (in - blurred). applies wmark as a watermark on the image with strength pixdiff, with an origin at (tx, ty) A demonstration of most of the filters can be found at: http://www.develop-help.com/imager/filters.html (This is a slow link.)

Color transformations
You can use the convert method to transform the color space of an image using a matrix. For ease of use some presets are provided. The convert method can be used to: convert an RGB or RGBA image to grayscale. convert a grayscale image to RGB. extract a single channel from an image. set a given channel to a particular value (or from another channel) The currently defined presets are: converts an RGBA image into a grayscale image with alpha channel, or an RGB image into a grayscale image without an alpha channel. This weights the RGB channels at 22.2%, 70.7% and 7.1% respectively. removes the alpha channel from a 2 or 4 channel image. An identity for other images. extracts the first channel of the image into a single channel image extracts the second channel of the image into a single channel image extracts the third channel of the image into a single channel image extracts the alpha channel of the image into a single channel image. If the image has 1 or 3 channels (assumed to be grayscale of RGB) then the resulting image will be all white. converts a grayscale image to RGB, preserving the alpha channel if any adds an alpha channel to a grayscale or RGB image. Preserves an existing alpha channel for a 2 or 4 channel image. For example, to convert an RGB image into a greyscale image: $new = $img->convert(preset=>'grey'); # or gray or to convert a grayscale image to an RGB image: $new = $img->convert(preset=>'rgb'); The presets aren't necessary simple constants in the code, some are generated based on the number of channels in the input image. If you want to perform some other colour transformation, you can use the 'matrix' parameter. For each output pixel the following matrix multiplication is done: channel[0] [ [ $c00, $c01, ... ] inchannel[0] [ ... ] = ... x [ ... ] channel[n-1] [ $cn0, ..., $cnn ] ] inchannel[max] 1 So if you want to swap the red and green channels on a 3 channel image: $new = $img->convert(matrix=>[ [ 0, 1, 0 ], [ 1, 0, 0 ], [ 0, 0, 1 ] ]); or to convert a 3 channel image to greyscale using equal weightings: $new = $img->convert(matrix=>[ [ 0.333, 0.333, 0.334 ] ])

Color Mappings
You can use the map method to map the values of each channel of an image independently using a list of lookup tables. It's important to realize that the modification is made inplace. The function simply returns the input image again or undef on failure. Each channel is mapped independently through a lookup table with 256 entries. The elements in the table should not be less than 0 and not greater than 255. If they are out of the 0..255 range they are clamped to the range. If a table does not contain 256 entries it is silently ignored. Single channels can mapped by specifying their name and the mapping table. The channel names are `red', `green', `blue', `alpha'. @map = map { int( $_/2 } 0..255; $img->map( red=>\@map ); It is also possible to specify a single map that is applied to all channels, alpha channel included. For example this applies a gamma correction with a gamma of 1.4 to the input image. $gamma = 1.4; @map = map { int( 0.5 + 255*($_/255)**$gamma ) } 0..255; $img->map(all=> \@map); The `all' map is used as a default channel, if no other map is specified for a channel then the `all' map is used instead. If we had not wanted to apply gamma to the alpha channel we would have used: $img->map(all=> \@map, alpha=>[]); Since `[]' contains fewer than 256 element the gamma channel is unaffected. It is also possible to simply specify an array of maps that are applied to the images in the rgba order. For example to apply maps to the `red' and `blue' channels one would use: $img->map(maps=>[\@redmap, [], \@bluemap]);

Transformations
Another special image method is transform. It can be used to generate warps and rotations and such features. It can be given the operations in postfix notation or the module Affix::Infix2Postfix can be used. Look in the test case t/t55trans.t for an example. transform() needs expressions (or opcodes) that determine the source pixel for each target pixel. Source expressions are infix expressions using any of the +, -, *, / or ** binary operators, the - unary operator, ( and ) for grouping and the sin() and cos() functions. The target pixel is input as the variables x and y. You specify the x and y expressions as xexpr and yexpr respectively. You can also specify opcodes directly, but that's magic deep enough that you can look at the source code. You can still use the transform() function, but the transform2() function is just as fast and is more likely to be enhanced and maintained. Later versions of Imager also support a transform2() class method which allows you perform a more general set of operations, rather than just specifying a spatial transformation as with the transform() method, you can also perform colour transformations, image synthesis and image combinations. transform2() takes an reference to an options hash, and a list of images to operate one (this list may be empty): my %opts; my @imgs; ... my $img = Imager::transform2(\%opts, @imgs) or die "transform2 failed: $Imager::ERRSTR"; The options hash may define a transformation function, and optionally: width - the width of the image in pixels. If this isn't supplied the width of the first input image is used. If there are no input images an error occurs. height - the height of the image in pixels. If this isn't supplied the height of the first input image is used. If there are no input images an error occurs. constants - a reference to hash of constants to define for the expression engine. Some extra constants are defined by Imager The tranformation function is specified using either the expr or rpnexpr member of the options. You can supply infix expressions to transform 2 with the expr keyword. $opts{expr} = 'return getp1(w-x, h-y)' The 'expression' supplied follows this general grammar: ( identifier '=' expr ';' )* 'return' expr This allows you to simplify your expressions using variables. A more complex example might be: $opts{expr} = 'pix = getp1(x,y); return if(value(pix)>0.8,pix*0.8,pix)' Currently to use infix expressions you must have the Parse::RecDescent module installed (available from CPAN). There is also what might be a significant delay the first time you run the infix expression parser due to the compilation of the expression grammar. You can supply postfix or reverse-polish notation expressions to transform2() through the rpnexpr keyword. The parser for rpnexpr emulates a stack machine, so operators will expect to see their parameters on top of the stack. A stack machine isn't actually used during the image transformation itself. You can store the value at the top of the stack in a variable called foo using !foo and retrieve that value again using @foo. The !foo notation will pop the value from the stack. An example equivalent to the infix expression above: $opts{rpnexpr} = 'x y getp1 !pix @pix value 0.8 gt @pix 0.8 * @pix ifp' transform2() has a fairly rich range of operators. multiplication, addition, subtraction, division, remainder and exponentiation. Multiplication, addition and subtraction can be used on colour values too - though you need to be careful - adding 2 white values together and multiplying by 0.5 will give you grey, not white. Division by zero (or a small number) just results in a large number. Modulo zero (or a small number) results in zero. Some basic trig functions. They work in radians, so you can't just use the hue values. Find the distance between two points. This is handy (along with atan2()) for producing circular effects. Find the square root. I haven't had much use for this since adding the distance() function. Find the absolute value. Get the pixel at position (x,y) from the first, second or third image respectively. I may add a getpn() function at some point, but this prevents static checking of the instructions against the number of images actually passed in. Separates a colour value into it's value (brightness), hue (colour) and saturation elements. Use hsv() to put them back together (after suitable manipulation). Separates a colour value into it's red, green and blue colours. Use rgb(r,g,b) to put it back together. Convert a value to an integer. Uses a C int cast, so it may break on large values. A simple (and inefficient) if function. Relational operators (typically used with if()). Since we're working with floating point values the equalities are 'near equalities' - an epsilon value is used. Basic logical operators. A few examples: tiles a smaller version of the input image over itself where the colour has a saturation over 0.7. tiles the input image over itself so that at the top of the image the full-size image is at full strength and at the bottom the tiling is most visible. replace pixels that are white or almost white with a palish blue Tiles the input image overitself where the image isn't white or almost white. Produces a spiral. A spiral built on top of a colour wheel. For details on expression parsing see the Imager::Expr manpage. For details on the virtual machine used to transform the images, see the Imager::regmach.pod manpage.

Matrix Transformations
Rather than having to write code in a little language, you can use a matrix to perform transformations, using the matrix_transform() method: my $im2 = $im->matrix_transform(matrix=>[ -1, 0, $im->getwidth-1, 0, 1, 0, 0, 0, 1 ]); By default the output image will be the same size as the input image, but you can supply the xsize and ysize parameters to change the size. Rather than building matrices by hand you can use the Imager::Matrix2d module to build the matrices. This class has methods to allow you to scale, shear, rotate, translate and reflect, and you can combine these with an overloaded multiplication operator. WARNING: the matrix you provide in the matrix operator transforms the co-ordinates within the destination image to the co-ordinates within the source image. This can be confusing. Since Imager has 3 different fairly general ways of transforming an image spatially, this method also has a yatf() alias. Yet Another Transformation Function.

Masked Images
Masked images let you control which pixels are modified in an underlying image. Where the first channel is completely black in the mask image, writes to the underlying image are ignored. For example, given a base image called $img: my $mask = Imager->new(xsize=>$img->getwidth, ysize=>getheight, channels=>1); # ... draw something on the mask my $maskedimg = $img->masked(mask=>$mask); You can specifiy the region of the underlying image that is masked using the left, top, right and bottom options. If you just want a subset of the image, without masking, just specify the region without specifying a mask.

Plugins
It is possible to add filters to the module without recompiling the module itself. This is done by using DSOs (Dynamic shared object) avaliable on most systems. This way you can maintain our own filters and not have to get me to add it, or worse patch every new version of the Module. Modules can be loaded AND UNLOADED at runtime. This means that you can have a server/daemon thingy that can do something like: load_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n"; %hsh=(a=>35,b=>200,type=>lin_stretch); $img->filter(%hsh); unload_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n"; $img->write(type=>'pnm',file=>'testout/t60.jpg') || die "error in write()\n"; Someone decides that the filter is not working as it should - dyntest.c modified and recompiled. load_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n"; $img->filter(%hsh); An example plugin comes with the module - Please send feedback to addi@umich.edu if you test this. Note: This seems to test ok on the following systems: Linux, Solaris, HPUX, OpenBSD, FreeBSD, TRU64/OSF1, AIX. If you test this on other systems please let me know.

Tags
Image tags contain meta-data about the image, ie. information not stored as pixels of the image. At the perl level each tag has a name or code and a value, which is an integer or an arbitrary string. An image can contain more than one tag with the same name or code. You can retrieve tags from an image using the tags() method, you can get all of the tags in an image, as a list of array references, with the code or name of the tag followed by the value of the tag: my @alltags = $img->tags; or you can get all tags that have a given name: my @namedtags = $img->tags(name=>$name); or a given code: my @tags = $img->tags(code=>$code); You can add tags using the addtag() method, either by name: my $index = $img->addtag(name=>$name, value=>$value); or by code: my $index = $img->addtag(code=>$code, value=>$value); You can remove tags with the deltag() method, either by index: $img->deltag(index=>$index); or by name: $img->deltag(name=>$name); or by code: $img->deltag(code=>$code); In each case deltag() returns the number of tags deleted. When you read a GIF image using read_multi(), each image can include the following tags: the offset of the image from the left of the "screen" ("Image Left Position") the offset of the image from the top of the "screen" ("Image Top Position") non-zero if the image was interlaced ("Interlace Flag") the size of the logical screen ("Logical Screen Width", "Logical Screen Height") Non-zero if this image had a local color map. The index in the global colormap of the logical screen's background color. This is only set if the current image uses the global colormap. The index of the color in the colormap used for transparency. If the image has a transparency then it is returned as a 4 channel image with the alpha set to zero in this palette entry. ("Transparent Color Index") The delay until the next frame is displayed, in 1/100 of a second. ("Delay Time"). whether or not a user input is expected before continuing (view dependent) ("User Input Flag"). how the next frame is displayed ("Disposal Method") the number of loops from the Netscape Loop extension. This may be zero. the first block of the first gif comment before each image. Where applicable, the ("name") is the name of that field from the GIF89 standard. The following tags are set in a TIFF image when read, and can be set to control output: The value of the ResolutionUnit tag. This is ignored on writing if the i_aspect_only tag is non-zero. The following tags are set when a Windows BMP file is read: The type of compression, if any. The number of important colors as defined by the writer of the image. Some standard tags will be implemented as time goes by: The spatial resolution of the image in pixels per inch. If the image format uses a different scale, eg. pixels per meter, then this value is converted. A floating point number stored as a string. If this is non-zero then the values in i_xres and i_yres are treated as a ratio only. If the image format does not support aspect ratios then this is scaled so the smaller value is 72dpi. box, arc, circle do not support antialiasing yet. arc, is only filled as of yet. Some routines do not return $self where they should. This affects code like this, `$img->box()->arc()' where an object is expected. When saving Gif images the program does NOT try to shave of extra colors if it is possible. If you specify 128 colors and there are only 2 colors used - it will have a 128 colortable anyway. Arnar M. Hrafnkelsson, addi@umich.edu, and recently lots of assistance from Tony Cook. See the README for a complete list. perl(1), Imager::Color(3), Imager::Font(3), Imager::Matrix2d(3), Affix::Infix2Postfix(3), Parse::RecDescent(3) http://www.eecs.umich.edu/~addi/perl/Imager/