This is Info file pm.info, produced by Makeinfo version 1.68 from the
input file bigpm.texi.


File: pm.info,  Node: Image/ParseGIF,  Next: Image/README,  Prev: Image/Magick,  Up: Module List

Parse a GIF image into its compenent parts.
*******************************************

NAME
====

   Image::ParseGIF - Parse a GIF image into its compenent parts.

SYNOPSIS
========

     use Image::ParseGIF;

     $gif = new Image::ParseGIF ("image.gif") or die "failed to parse: $@\n";

     # write out a deanimated version, showing only the first frame
     $gif->deanimate(0);

     #  same again, manually printing each part
     print $gif->header;
     print $gif->part(0);
     print $gif->trailer;
     #  or, without passing scalars around:
     $gif->print_header;
     $gif->print_part(0);
     $gif->print_trailer;

     # send an animated gif frame by frame
     #  - makes for a progress bar which really means something
     $gif = new Image::ParseGIF ("progress.gif") or die "failed to parse: $@\n";

     $gif->print_header;

     $gif->print_percent(0.00);	# starting...
     do_some_work_stage1();

     $gif->print_percent(0.10);	# 10% complete
     do_some_work_stage2();

     $gif->print_percent(0.25);	# 25% complete
     do_some_work_stage3();

     $gif->print_percent(0.70);	# 70% complete
     do_some_work_stage4();

     $gif->print_percent(1.00);	# done!

     $gif->print_trailer;

DESCRIPTION
===========

   This module parses a Graphics Interchange Format (GIF) image into its
component 'parts'. A GIF is essentially made up of one or more images -
multiple images typically are used for animated gifs.

PURPOSE
-------

   This module was written to allow a web application to display the status
of a request, without resorting to scripting or polling the server via
client refresh.

   Most web browsers (at least Netscape 2.02 & 4.05, Opera 3.21 and
Internet Explorer 4.0) show each frame as soon as it is received.
(Indeed, the GIF format is block-based so any image viewer which can
handle animated GIFs should operate similarly.) So, if we can arrange for
the parts of a progress bar image to be delivered to the client in
sympathy with the request's progress, we'll have made a dandy real-time
feedback mechanism. Contrast this with the common fixed animation used at
many sites, which are uncorrelated to the request state and not at all
realistic.

   One implementation of this status mechanism involves the main
application returning a page containing an image tag to a 'status' script
(e.g.  <img src="status.cgi?id="request_id">). The status script
interrogates the request's status (perhaps by reading from a pipe), and
prints image frames as the request progresses.

   At the moment the image is wholly read into memory. File pointers could
be used to operate from disk, however, given that most web images are on
the order of 1-100k, I don't see a lot of benefit in bothering to do so.
Also, if a persistant application is used (i.e. FCGI), the same image can
be reused for many requests.

BACKGROUND
----------

   A gif image consists of:

  1. a 'header' (including the GIF header (signature string) and logical
     screen descriptor)

  2. a global colour map

  3. zero or more 'graphic blocks' or 'extensions'

        * a block/extension header

        * one or more sub-blocks per part

  4. a trailer

        Note that this module groups the GIF header, logical screen
descriptor and any global colour map into the 'header' part.

   There are two types of 'descriptor blocks/extensions' defined in the GIF
specification [1]: an image descriptor; or an extension. Extensions can
contain 'control' information for things like animated gifs. Each
descriptor block/extension has its own 'header', often followed by one or
more data blocks. This module extracts only image descriptors and graphic
control extensions. Moreover, this module treats associated descriptor
blocks and extensions as a 'part' - an image 'part' is considered to be
the extension/s leading up to an image descriptor, plus the image
descriptor.

CONSTRUCTOR / CLASS METHODS
===========================

   In general, all `Image::ParseGIF' methods return undef on error,
possibly with an explanatory message in $@.

autoflush ( STATE )
     Class method (i.e. Image::ParseGIF::autoflush(0)). Sets default
     autoflush() state for new output streams. On by default.

new ( [FILENAME] )
new ( FILENAME [,  ARGUMENTS ] )
new ( FILENAME [, {ARGUMENTS}] )
     Creates a new `Image::ParseGIF' object.

     If FILENAME is supplied, opens and parses the given file.

     ARGUMENTS may be:

    'debug' (natural number)
          Set the debug level.

    'output' (IO::Handle/filehandle/glob)
          Sets the default output stream (default STDOUT). (See perl's
          binmode() regarding writing binary output.)

    'invert' (natural number)
          Adjusts the colour inversion feature (default 0 is off).

    'posterize' (natural number) =item 'posterise' (natural number)
          Adjusts the colour posterization (high pass filtering) feature
          (default 0 is off, positive values increase the resulting gamut).

    'desaturate' (natural number)
          Adjusts the colour-to-grayscale feature (default 0 is off).

METHODS
=======

debug ( LEVEL )
     If LEVEL is omitted, returns the current debug level setting.

     If LEVEL is defined, sets the current debug level.  The higher the
     debug level, the more output.

invert ( EXPR )
     If EXPR is omitted, returns the current colour inversion setting.

     If EXPR is defined, sets the current colour inversion setting.  Zero
     is off, nonzero inverts RGB colour table values, leaving each one as
     a photo-negative colour instead.  Default is 0.

posterize ( EXPR ) =item posterise ( EXPR )
     If EXPR is omitted, returns the current colour posterization setting.

     If EXPR is defined (N), sets the current colour posterization setting.
     Zero is off, nonzero posterizes RGB colour table values, leaving each
     one to be one of N colors. Default is 0.

desaturate ( EXPR )
     If EXPR is omitted, returns the current colour desaturization setting.

     If EXPR is defined, sets the current colour desaturization setting.
     Zero is off, nonzero desaturizes RGB colour table values, leaving
     each one as a mean grayscale value.  Default is 0.

open ( FILENAME )
     Opens the given file and parses it.

parse ( IO )
     Parse a GIF, reading from a given filehandle / IO::Handle.

(header|trailer)
     Returns the image (header|trailer) as a scalar.

parts
     Returns a list of the image parts in array context, or the number of
     parts in scalar context. Does not include header or trailer.

part ( PART )
     Returns an image part as a scalar. If PART == undef, returns header;
     if PART > number of parts, returns trailer.

output ( IO )
     Specifies the default output filehandle / IO::Handle for all
     subsequent print_ calls. (See perl's binmode() regarding writing
     binary output.)

print_(header|trailer) ( [IO] )
     Prints the (header|trailer) to the supplied / default output stream.

print_part ( [PART] [, IO] )
     Prints the given PART to the supplied / default output stream.

print_parts ( [PART] [, IO] )
     Remembers which part it was up to (PreviousPART), prints from from
     PreviousPART to PART to the supplied / default output stream.

print_percent ( PERCENT [, IO ] )
     Prints PERCENT percent of the image frames. Remembers where it was up
     to, and will only print increasing part numbers (i.e. it won't
     duplicate parts). Note you'll still need to print the header and
     trailer.

deanimate ( [PART] [, IO ] )
     Prints header, given part (or part 0 if unspecified) and trailer to
     the supplied / default output stream.

NOTES
=====

   You should be able to parse an image contained in any object which has
a read() method (e.g. IO::Scalar), however the object will have to support
the OFFSET read() argument. As at version 1.114, IO::Scalar does not.

   For example:   $io = new IO::File ('blah');   $gif = new
Image::ParseGIF;   $gif->parse($io) or die "failed to parse: $@\n";

"BUGS"
======


     It'd be nice to have a more generic interface to handle all GIF
     extensions, etc.


     And from the "In case you've ever wondered" department:

     Natural Number (http://mathworld.wolfram.com/NaturalNumber.html)

     "A positive integer 1, 2, 3, ... ([ref]). The set of natural numbers
     is denoted N or Z+. Unfortunately, 0 is sometimes also included in the
     list of "natural" numbers (Bourbaki 1968, Halmos 1974), and there
     seems to be no general agreement about whether to include it.  In
     fact, Ribenboim (1996) states "Let [P] be a set of natural numbers;
     whenever convenient, it may be assumed that [0 <element of> P].""

COPYRIGHT
=========

   Copyright (c) 1999/2000 University of New South Wales Benjamin Low
<b.d.low@unsw.edu.au>. All rights reserved.

   Colour-table portions added 1 June 2000 Ed Halley <ed@explorati.com>.

   This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

   This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.  See the Artistic License for more
details.

AUTHORS
=======

   Benjamin Low <b.d.low@unsw.edu.au>

   Ed Halley <ed@explorati.com>

SEE ALSO
========

   This code was based on the CGI 89a spec [1] and the Image::DeAnim module
by Ken MacFarlane.

   [1] http://member.aol.com/royalef/gif89a.txt


File: pm.info,  Node: Image/README,  Next: Image/Size,  Prev: Image/ParseGIF,  Up: Module List

Perl module to easily grab images from the 'net.
************************************************

NAME
====

   Image::Grab - Perl module to easily grab images from the 'net.

Behavior Changes:
=================

   Since 1.1, I've made Image::Grab look for background images.  This
could cause you problems if the background images match your regexps or if
you use indexes.

   Since 0.9.5, I've added the search_url method in lieu of overloading
regexp.  This means that you'll have to check your scripts.

   Since 0.9.3, I've added the do_posix method and changed the behavior so
that POSIX date substitution is only done if do_posix is set.  This is
because strftime appears to garble the 128th character and on in long
string substitutions.  I've seen this in Digital Unix, Linux and Solaris.

Installation:
=============

   You must have the following modules already installed:

     Digest::MD5 2.07
     HTML::Parser 2.20
     HTML::Tree 0.51
     MIME::Base64 2.11
     URI 1.02
     libnet 1.0606
     libwww-perl 5.43

   (Earlier versions of some packages may work, but I haven't tested them.)

     $ perl Makefile.PL
     $ make test
     $ make install

   And that should do it.  Let me know of any problems
(<mah@everybody.org>)

Testing:
========

   Unless you have cookies for www.chron.com, the cookies.t test will be
skipped.  The tests rely on cookies being set in your ~/.netscape/cookies
file.  You could set these yourself by visiting the Huston Chronicle
website (http://www.chron/content/comics) and getting an account.  If you
don't do this, these tests won't even run.

   If you are testing this from behind a firewall, be sure that your proxy
environment variables are set correctly (e.g.
http_proxy=http://wwwproxy:80/).

Response:
=========

   If you care to, let me know how you are using this module.  It's nice
to know what different people are using this for.


File: pm.info,  Node: Image/Size,  Next: Image/Xbm,  Prev: Image/README,  Up: Module List

read the dimensions of an image in several popular formats
**********************************************************

NAME
====

   Image::Size - read the dimensions of an image in several popular formats

SYNOPSIS
========

     use Image::Size;
     # Get the size of globe.gif
     ($globe_x, $globe_y) = imgsize("globe.gif");
     # Assume X=60 and Y=40 for remaining examples

     use Image::Size 'html_imgsize';
     # Get the size as 'width="X" height="Y"' for HTML generation
     $size = html_imgsize("globe.gif");
     # $size == 'width="60" height="40"'

     use Image::Size 'attr_imgsize';
     # Get the size as a list passable to routines in CGI.pm
     @attrs = attr_imgsize("globe.gif");
     # @attrs == ('-width', 60, '-height', 40)

     use Image::Size;
     # Get the size of an in-memory buffer
     ($buf_x, $buf_y) = imgsize($buf);

DESCRIPTION
===========

   The *Image::Size* library is based upon the `wwwis' script written by
Alex Knowles *(alex@ed.ac.uk)*, a tool to examine HTML and add 'width' and
'height' parameters to image tags. The sizes are cached internally based on
file name, so multiple calls on the same file name (such as images used in
bulleted lists, for example) do not result in repeated computations.

   *Image::Size* provides three interfaces for possible import:

imgsize(stream)
     Returns a three-item list of the X and Y dimensions (width and
     height, in that order) and image type of stream. Errors are noted by
     undefined (undef) values for the first two elements, and an error
     string in the third.  The third element can be (and usually is)
     ignored, but is useful when sizing data whose type is unknown.

html_imgsize(stream)
     Returns the width and height (X and Y) of stream pre-formatted as a
     single string `'width="X" height="Y"'' suitable for addition into
     generated HTML IMG tags. If the underlying call to `imgsize' fails,
     undef is returned. The format returned should be dually suited to
     both HTML and XHTML.

attr_imgsize(stream)
     Returns the width and height of stream as part of a 4-element list
     useful for routines that use hash tables for the manipulation of
     named parameters, such as the Tk or CGI libraries. A typical return
     value looks like `("-width", X, "-height", Y)'. If the underlying
     call to `imgsize' fails, undef is returned.

   By default, only `imgsize()' is imported. Any one or combination of the
three may be imported, or all three may be with the tag :all.

Input Types
-----------

   The sort of data passed as stream can be one of three forms:

string
     If an ordinary scalar (string) is passed, it is assumed to be a file
     name (either absolute or relative to the current working directory of
     the process) and is searched for and opened (if found) as the source
     of data.  Possible error messages (see DIAGNOSTICS below) may include
     file-access problems.

scalar reference
     If the passed-in stream is a scalar reference, it is interpreted as
     pointing to an in-memory buffer containing the image data.

          # Assume that &read_data gets data somewhere (WWW, etc.)
          $img = &read_data;
          ($x, $y, $id) = imgsize(\$img);
          # $x and $y are dimensions, $id is the type of the image

Open file handle
     The third option is to pass in an open filehandle (such as an object
     of the IO::File class, for example) that has already been associated
     with the target image file. The file pointer will necessarily move,
     but will be restored to its original position before subroutine end.

          # $fh was passed in, is IO::File reference:
          ($x, $y, $id) = imgsize($fh);
          # Same as calling with filename, but more abstract.

Recognizd Formats
-----------------

   Image::Size understands and sizes data in the following formats:


     GIF


     JPG


     XBM


     XPM


     PPM family (PPM/PGM/PBM)


     PNG


     TIF


     BMP

   When using the `imgsize' interface, there is a third, unused value
returned if the programmer wishes to save and examine it. This value is
the three- letter identity of the data type. This is useful when operating
on open file handles or in-memory data, where the type is as unknown as
the size.  The two support routines ignore this third return value, so
those wishing to use it must use the base `imgsize' routine.

DIAGNOSTICS
===========

   The base routine, `imgsize', returns undef as the first value in its
list when an error has occured. The third element contains a descriptive
error message.

   The other two routines simply return undef in the case of error.

MORE EXAMPLES
=============

   The *attr_imgsize* interface is also well-suited to use with the Tk
extension:

     $image = $widget->Photo(-file => $img_path, attr_imgsize($img_path));

   Since the Tk::Image classes use dashed option names as CGI does, no
further translation is needed.

   This package is also well-suited for use within an Apache web server
context.  File sizes are cached upon read (with a check against the
modified time of the file, in case of changes), a useful feature for a
mod_perl environment in which a child process endures beyond the lifetime
of a single request.  Other aspects of the mod_perl environment cooperate
nicely with this module, such as the ability to use a sub-request to fetch
the full pathname for a file within the server space. This complements the
HTML generation capabilities of the CGI module, in which `CGI::img' wants
a URL but `attr_imgsize' needs a file path:

     # Assume $Q is an object of class CGI, $r is an Apache request object.
     # $imgpath is a URL for something like "/img/redball.gif".
     $r->print($Q->img({ -src => $imgpath,
                         attr_imgsize($r->lookup_uri($imgpath)->filename) }));

   The advantage here, besides not having to hard-code the server document
root, is that Apache passes the sub-request through the usual request
lifecycle, including any stages that would re-write the URL or otherwise
modify it.

CAVEATS
=======

   Caching of size data can only be done on inputs that are file names.
Open file handles and scalar references cannot be reliably transformed
into a unique key for the table of cache data. Buffers could be cached
using the MD5 module, and perhaps in the future I will make that an
option. I do not, however, wish to lengthen the dependancy list by another
item at this time.

SEE ALSO
========

   `http://www.tardis.ed.ac.uk/~ark/wwwis/' for a description of `wwwis'
and how to obtain it.

AUTHORS
=======

   Perl module interface by Randy J. Ray *(rjray@tsoft.com)*, original
image-sizing code by Alex Knowles *(alex@ed.ac.uk)* and Andrew Tong
*(werdna@ugcs.caltech.edu)*, used with their joint permission.

   Some bug fixes submitted by Bernd Leibing
*(bernd.leibing@rz.uni-ulm.de)*.  PPM/PGM/PBM sizing code contributed by
Carsten Dominik *(dominik@strw.LeidenUniv.nl)*. Tom Metro
*(tmetro@vl.com)* re-wrote the JPG and PNG code, and also provided a PNG
image for the test suite. Dan Klein *(dvk@lonewolf.com)* contributed a
re-write of the GIF code.  Cloyce Spradling *(cloyce@headgear.org)*
contributed TIFF sizing code and test images. Aldo Calpini
*(a.calpini@romagiubileo.it)* suggested support of BMP images (which I
*really* should have already thought of :-) and provided code to work
with. A patch to allow html_imgsize to produce valid output for XHTML, as
well as some documentation fixes was provided by Charles Levert
*(charles@comm.polymtl.ca)*.


File: pm.info,  Node: Image/Xbm,  Next: Image/Xpm,  Prev: Image/Size,  Up: Module List

Load, create, manipulate and save xbm image files.
**************************************************

NAME
====

   Image::Xbm - Load, create, manipulate and save xbm image files.

SYNOPSIS
========

     use Image::Xbm ;

     my $j = Image::Xbm->new( -file, 'balArrow.xbm' ) ;

     my $i = Image::Xbm->new( -width => 10, -height => 16 ) ;

     my $h = $i->new ; # Copy of $i

     my $p = Image::Xbm->new_from_string( "###\n#-#\n###" ) ;

     my $q = $p->new_from_string( "H##", "#-#", "###" ) ;

     my $s = $q->serialse ; # Compresses a little too.
     my $t = Image::Xbm->new_from_serialsed( $s ) ;

     $i->xybit( 5, 8, 1 ) ;           # Set a bit
     print '1' if $i->xybit( 9, 3 ) ; # Get a bit
     print $i->xy( 4, 5 ) ;           # Will print black or white

     $i->vec( 24, 0 ) ;            # Set a bit using a vector offset
     print '1' if $i->vec( 24 ) ;  # Get a bit using a vector offset

     print $i->get( -width ) ;     # Get and set object and class attributes
     $i->set( -height, 15 ) ;

     $i->load( 'test.xbm' ) ;
     $i->save ;

     print "equal\n" if $i->is_equal( $j ) ;

     print $j->as_string ;

     #####-
     ###---
     ###---
     #--#--
     #---#-
     -----#

     print $j->as_binstring ;

     1111101110001110001001001000100000010000

   View an xbm file from the command line:

     % perl -MImage::Xbm -e'print Image::Xbm->new(-file,shift)->as_string' file

   Create an xbm file from the command line:

     % perl -MImage::Xbm -e'Image::Xbm->new_from_string("###\n#-#\n-#-")->save("test.xbm")'

DESCRIPTION
===========

   This class module provides basic load, manipulate and save
functionality for the xbm file format. It inherits from `Image::Base'
which provides additional manipulation functionality, e.g.
new_from_image(). See the `Image::Base' pod for information on adding your
own functionality to all the `Image::Base' derived classes.

new()
-----

     my $i = Image::Xbm->new( -file => 'test.xbm' ) ;
     my $j = Image::Xbm->new( -width => 12, -height => 18 ) ;
     my $k = $i->new ;

   We can create a new xbm image by reading in a file, or by creating an
image from scratch (all the bits are unset by default), or by copying an
image object that we created earlier.

   If we set `-file' then all the other arguments are ignored (since
they're taken from the file). If we don't specify a file, `-width' and
`-height' are mandatory.

`-file'
     The name of the file to read when creating the image. May contain a
     full path.  This is also the default name used for loading and
     saveing, though it can be overridden when you load or save.

`-width'
     The width of the image; taken from the file or set when the object is
     created; read-only.

`-height'
     The height of the image; taken from the file or set when the object
     is created; read-only.

`-hotx'
     The x-coord of the image's hotspot; taken from the file or set when
     the object is created. Set to -1 if there is no hotspot.

`-hoty'
     The y-coord of the image's hotspot; taken from the file or set when
     the object is created. Set to -1 if there is no hotspot.

`-bits'
     The bit vector that stores the image; read-only.

new_from_string()
-----------------

     my $p = Image::Xbm->new_from_string( "###\n#-#\n###" ) ;
     my $q = $p->new_from_string( "H##", "#-#", "###" ) ;
     my $r = $p->new_from_string( $p->as_string ) ;

   Create a new bitmap from a string or from an array or list of strings.
If you want to use different characters you can:

     Image::Xbm->set( -setch => 'X', -unsetch => ' ' ) ;
     my $s = $p->new_from_string( "XXX", "X X", "XhX" ) ;

   You can also specify a hotspot by making one of the characters a 'H'
(set bit hotspot) or 'h' (unset bit hotspot) - you can use different
characters by setting `-sethotch' and `-unsethotch' respectively.

new_from_serialised()
---------------------

     my $i = Image::Xbm->new_from_serialised( $s ) ;

   Creates an image from a string created with the `serialse()' method.
Since such strings are a little more compressed than xbm files or
Image::Xbm objects they might be useful if storing a lot of bitmaps, or
for transferring bitmaps over comms links.

serialise()
-----------

     my $s = $i->serialise ;

   Creates a string version of the image which can be completed recreated
using the `new_from_serialised' method.

get()          my $width = $i->get( -width ) ;     my( $hotx, $hoty ) = $i->get( -hotx, -hoty ) ;
-------------------------------------------------------------------------------------------------

   Get any of the object's attributes. Multiple attributes may be
requested in a single call.

   See `xy' and vec to get/set bits of the image itself.

set()
-----

     $i->set( -hotx => 120, -hoty => 32 ) ;

   Set any of the object's attributes. Multiple attributes may be set in a
single call. Except for `-setch' and `-unsetch' all attributes are object
attributes; some attributes are read-only.

   See `xy' and vec to get/set bits of the image itself.

class attributes
----------------

     Image::Xbm->set( -setch => 'X' ) ;
     $i->set( -setch => '@', -unsetch => '*' ) ;

`-setch'
     The character to print set bits as when using as_string, default is
     '#'.  This is a class attribute accessible from the class or an
     object via get and set.

`-unsetch'
     The character to print set bits as when using as_string, default is
     '-'.  This is a class attribute accessible from the class or an
     object via get and set.

`-sethotch'
     The character to print set bits as when using as_string, default is
     'H'.  This is a class attribute accessible from the class or an
     object via get and set.

`-unsethotch'
     The character to print set bits as when using as_string, default is
     'h'.  This is a class attribute accessible from the class or an
     object via get and set.

xybit()
-------

     $i->xy( 4, 11, 1 ) ;      # Set the bit at point 4,11
     my $v = $i->xy( 9, 17 ) ; # Get the bit at point 9,17

   Get/set bits using x, y coordinates; coordinates start at 0.

xy()
----

     $i->xy( 4, 11, 'black' ) ;  # Set the bit from a colour at point 4,11
     my $v = $i->xy( 9, 17 ) ;   # Get the bit as a colour at point 9,17

   Get/set bits using colours using x, y coordinates; coordinates start at
0.

   If set with a colour of 'black' or a numeric value > 0 or a string not
matching /^#0+$/ then the bit will be set, otherwise it will be cleared.

   If you get a colour you will always get 'black' or 'white'.

vec()
-----

     $i->vec( 43, 0 ) ;      # Unset the bit at offset 43
     my $v = $i->vec( 87 ) ; # Get the bit at offset 87

   Get/set bits using vector offsets; offsets start at 0.

load()
------

     $i->load ;
     $i->load( 'test.xbm' ) ;

   Load the image whose name is given, or if none is given load the image
whose name is in the `-file' attribute.

save()
------

     $i->save ;
     $i->save( 'test.xbm' ) ;

   Save the image using the name given, or if none is given save the image
using the name in the `-file' attribute. The image is saved in xbm format,
e.g.

     #define test_width 6
     #define test_height 6
     static unsigned char test_bits[] = {
      0x1f, 0x07, 0x07, 0x09, 0x11, 0x20 } ;

is_equal()
----------

     print "equal\n" if $i->is_equal( $j ) ;

   Returns true (1) if the images are equal, false (0) otherwise. Note that
hotspots and filenames are ignored, so we compare width, height and the
actual bits only.

as_string()
-----------

     print $i->as_string ;

   Returns the image as a string, e.g.

     #####-
     ###---
     ###---
     #--#--
     #---#-
     -----#

   The characters used may be changed by setting the `-setch' and
`-unsetch' characters. If you give as_string a parameter it will print out
the hotspot if present using `-sethotch' or `-unsethotch' as appropriate,
e.g.

     print $n->as_string( 1 ) ;

     H##
     #-#
     ###

as_binstring()
--------------

     print $i->as_binstring ;

   Returns the image as a string of 0's and 1's, e.g.

     1111101110001110001001001000100000010000

CHANGES
=======

   2000/11/09

   Added Jerrad Pierce's patch to allow load() to accept filehandles or
strings; will document in next release.

   2000/05/05

   Added new_from_serialised() and serialise() methods.

   2000/05/04

   Made xy() compatible with Image::Base, use xybit() for the earlier
functionality.

   2000/05/01

   Improved speed of vec(), xy() and as_string().

   Tried use integer to improve speed but according to Benchmark it made
the code slower so I dropped it; interestingly perl 5.6.0 was around 25%
slower than perl 5.004 with and without use integer.

   2000/04/30

   Created.

AUTHOR
======

   Mark Summerfield. I can be contacted as <summer@perlpress.com> - please
include the word 'xbm' in the subject line.

COPYRIGHT
=========

   Copyright (c) Mark Summerfield 2000. All Rights Reserved.

   This module may be used/distributed/modified under the LGPL.


File: pm.info,  Node: Image/Xpm,  Next: Imager,  Prev: Image/Xbm,  Up: Module List

Load, create, manipulate and save xpm image files.
**************************************************

NAME
====

   Image::Xpm - Load, create, manipulate and save xpm image files.

SYNOPSIS
========

     use Image::Xpm;

     my $j = Image::Xpm->new(-file, 'Camel.xpm');

     my $i = Image::Xpm->new(-width => 10, -height => 16);

     my $h = $i->new; # Copy of $i

     $i->xy(5, 8, 'red');       # Set a colour (& add to palette if necessary)
     print $i->xy(9, 3);        # Get a colour

     $i->xy(120, 130, '#1256DD');
     $i->xy(120, 130, $i->rgb2colour(66, 0x4D, 31));

     $i->vec(24, '#808080');    # Set a colour using a vector offset
     print $i->vec(24);         # Get a colour using a vector offset

     print $i->get(-width);     # Get and set object attributes
     $i->set(-height, 15);

     $i->load('test.xpm');
     $i->save;

     # Changing just the palette
     $i->add_colours(qw(red green blue #123456 #C0C0C0));
     $i->del_colour('blue');

DESCRIPTION
===========

   This class module provides basic load, manipulate and save
functionality for the xpm file format. It inherits from `Image::Base'
which provides additional manipulation functionality, e.g.
new_from_image(). See the `Image::Base' pod for information on adding your
own functionality to all the Image::Base derived classes.

new()
-----

     my $i = Image::Xpm->new(-file => 'test.xpm');
     my $j = Image::Xpm->new(-width => 12, -height => 18);
     my $k = $i->new;

   We can create a new xpm image by reading in a file, or by creating an
image from scratch (all the pixels are white by default), or by copying an
image object that we created earlier.

   If we set `-file' then all the other arguments are ignored (since
they're taken from the file). If we don't specify a file, `-width' and
`-height' are mandatory and `-cpp' will default to 1 unless specified
otherwise.

`-file'
     The name of the file to read when creating the image. May contain a
     full path.  This is also the default name used for loading and
     saveing, though it can be overridden when you load or save.

`-width'
     The width of the image; taken from the file or set when the object is
     created; read-only.

`-height'
     The height of the image; taken from the file or set when the object
     is created; read-only.

`-cpp'
     Characters per pixel. Commonly 1 or 2, default is 1 for images
     created by the module; read-only.

     See the example for how to change an image's cpp.

`-hotx'
     The x-coord of the image's hotspot; taken from the file or set when
     the object is created. Set to -1 if there is no hotspot.

`-hoty'
     The y-coord of the image's hotspot; taken from the file or set when
     the object is created. Set to -1 if there is no hotspot.

`-ncolours'
     The number of unique colours in the palette. The image may not be
     using all of them; read-only.

`-cindex'
     An hash whose keys are colour names, e.g. '#123456' or 'blue' and
     whose values are the palette names, e.g. ' ', '#', etc; read-only. If
     you want to add more colours to the image itself simply write pixels
     with the new colours using `xy'; if you want to add more colours to
     the palette without necessarily using them in the image use
     `add_colours'.

`-palette'
     A hash whose keys are the palette names, e.g. ' ', '#', etc. and
     whose values are hashes of colour type x colour name pairs, e.g. `c
     => red', etc; read-only. If you want to add more colours to the image
     itself simply write pixels with the new colours using `xy'; if you
     want to add more colours to the palette without necessarily using
     them in the image use `add_colours'.

`-pixels'
     A string of palette names which constitutes the data for the image
     itself; read-only.

`-extname'
     The name of the extension text if any; commonly XPMEXT; read-only.

`-extlines'
     The lines of text of any extensions; read-only.

`-comments'
     An array (possibly empty) of comment lines that were in a file that
     was read in; they will be written out although we make no guarantee
     regarding their placement; read-only.

get()          my $width = $i->get(-width);     my ($hotx, $hoty) = $i->get(-hotx, -hoty);
------------------------------------------------------------------------------------------

   Get any of the object's attributes. Multiple attributes may be
requested in a single call.

   See `xy' and vec to get/set colours of the image itself.

set()
-----

     $i->set(-hotx => 120, -hoty => 32);

   Set any of the object's attributes. Multiple attributes may be set in a
single call; some attributes are read-only.

   See `xy' and vec to get/set colours of the image itself.

xy()
----

     $i->xy(4, 11, '#123454');    # Set the colour at point 4,11
     my $v = $i->xy(9, 17);       # Get the colour at point 9,17

   Get/set colours using x, y coordinates; coordinates start at 0. If the
colour does not exist in the palette it will be added automatically.

   When called to set the colour the value returned is characters used for
that colour in the palette; when called to get the colour the value
returned is the colour name, e.g. 'blue' or '#f0f0f0', etc, e.g.

     $colour = xy($x, $y);            # e.g. #123456
     $cc     = xy($x, $y, $colour);   # e.g. !

   We don't normally pick up the return value when setting the colour.

vec()
-----

     $i->vec(43, 0);      # Unset the bit at offset 43
     my $v = $i->vec(87); # Get the bit at offset 87

   Get/set bits using vector offsets; offsets start at 0. The offset of a
pixel is ((y * width * cpp) + (x * cpp)).

   The sort of return value depends on whether we are reading (getting) or
writing (setting) the colour - see `xy' for an explanation.

rgb2colour() and rgb2color()          $i->rgb2colour(0xff, 0x40, 0x80);    # Returns #ff4080     Image::Xpm->rgb2colour(10, 20, 30);  # Returns #0a141e
-------------------------------------------------------------------------------------------------------------------------------------------------------

   Convenience class or object methods which accept three integers and
return a colour name string.

load()
------

     $i->load;
     $i->load('test.xpm');

   Load the image whose name is given, or if none is given load the image
whose name is in the `-file' attribute.

save()
------

     $i->save;
     $i->save('test.xpm');

   Save the image using the name given, or if none is given save the image
using the name in the `-file' attribute. The image is saved in xpm format.

add_colours() and add_colors()
------------------------------

     $i->add_colours(qw(#C0C0DD red blue #123456));

   These are for adding colours to the palette; you don't need to use them
to set a pixel's colour - use `xy' for that.

   Add one or more colour names either as hex strings or as literal colour
names.  These are always added as type 'c' colours; duplicates are ignored.

   NB If you just want to set some pixels in colours that may not be in the
palette, simply do so using `xy' since new colours are added automatically.

del_colour() and del_color()
----------------------------

     $i->del_colour('green');

   Delete a colour from the palette; returns undef if the colour isn't in
the palette, false (0) if the colour is in the palette but also in the
image, or true (1) if the colour has been deleted (i.e. it was in the
palette but not in use in the image).

EXAMPLE
=======

Changing the -cpp of an image:
------------------------------

     my $i = Image::Xpm(-file => 'test1.xpm'); # test1.xpm has cpp == 1
     my $j = $i->new_from_image('Image::xpm', -cpp => 2);
     $j->save('test2.xpm');

     # Could have written 2nd line above as:
     my $j = $i->new_from_image(ref $i, -cpp => 2);

CHANGES
=======

   2000/11/09

   Added Jerrad Pierce's patch to allow load() to accept filehandles or
strings; will document in next release.

   2000/10/19

   Fixed bugs in xy() and vec() reported by Pat Gunn.

   2000/05/25

   Fixed a bug in the test file; fixed a bug in save() which affected xpm
extensions.

   2000/05/04

   Fixed bugs in xy(), vec(), save() and load().  Improved the test
program.

   2000/05/03

   Created.

AUTHOR
======

   Mark Summerfield. I can be contacted as <summer@perlpress.com> - please
include the word 'xpm' in the subject line.

COPYRIGHT
=========

   Copyright (c) Mark Summerfield 2000. All Rights Reserved.

   This module may be used/distributed/modified under the GPL.


File: pm.info,  Node: Imager,  Next: Imager/Expr,  Prev: Image/Xpm,  Up: Module List

Perl extension for Generating 24 bit Images
*******************************************

NAME
====

   Imager - Perl extension for Generating 24 bit Images

SYNOPSIS
========

     use Imager;

     init();
     $img = Imager->new();
     $img->open(file=>'image.ppm',type=>'ppm')
       || print "failed: ",$img->{ERRSTR},"\n";
     $scaled=$img->scale(xpixels=>400,ypixels=>400);
     $scaled->write(file=>'sc_image.ppm',type=>'ppm')
       || print "failed: ",$scaled->{ERRSTR},"\n";

DESCRIPTION
===========

   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=>3);

   The latter example creates a completely black image of width 400 and
height 300 and 4 channels.

   To create a color object call the function i_color_new,
`$color=i_color_new($r,$g,$b,$a)'. The parameters are all from 0 to 255
and are all converted to integers. Each is the red, green, blue, and alpha
component of the color respectively.  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 left 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.
Neither ppm nor tiff have 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.

   *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 i_color objects.  Note that the
local means algorithm needs much more cpu time but also gives considerable
better results than the median cut algorithm.

   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 `Quantization options' in this node.

   To see what Imager is compiled to support the following code snippet is
sufficient:

     use Imager;
     print "@{[keys %Imager::formats]}";

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 3 possible types of outputs:

callback
     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.

fd
     The file descriptor to save the images to.

file
     The name of the file to write to.

     %opts may also include the keys from `Gif options' in this node and
     `Quantization options' in this node.

   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.

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).

gif_each_palette
     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.

interlace
     The images are written interlaced if this is non-zero.

gif_delays
     A reference to an array containing the delays between images, in 1/100
     seconds.

gif_user_input
     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.

gif_disposal
     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.

gif_tran_color
     A reference to an Imager::Color object, which is the colour to use for
     the palette entry used to represent transparency in the palette.

gif_positions
     A reference to an array of references to arrays which represent screen
     positions for each image.

gif_loop_count
     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.

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.

colors
     A arrayref of colors that are fixed.  Note that some color generators
     will ignore this.

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

    none
          No transparency processing is done. (default)

    threshold
          Pixels more transparent that tr_threshold are rendered as
          transparent.

    errdiff
          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.

    ordered
          The ordered dither specified by tr_orddith is performed on the
          alpha channel.

tr_threshold
     The highest alpha value at which a pixel will be made transparent when
     transp is 'threshold'. (0-255, default 127)

tr_errdiff
     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).

tr_ordered
     The type of ordered dither to perform on the alpha channel when transp
     is 'orddith'.  Possible values are:

    random
          A semi-random map is used.  The map is the same each time.
          Currently the default (which may change.)

    dot8
          8x8 dot dither.

    dot4
          4x4 dot dither

    hline
          horizontal line dither.

    vline
          vertical line dither.

    "/line"
    slashline
          diagonal line dither

    '\line'
    backline
          diagonal line dither

    custom
          A custom dither matrix is used - see tr_map

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.

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

    none
          Only colors supplied in 'colors' are used.

    webmap
          The web color map is used (need url here.)

    addi
          The original code for generating the color map (Addi's code) is
          used.

     Other methods may be added in the future.

colors
     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.)

max_colors
     The maximum number of colors to use in the image.

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

    giflib
          The giflib native quantization function is used.

    closest
          The closest color available is used.

    perturb
          The pixel color is modified by perturb, and the closest color is
          chosen.

    errdiff
          An error diffusion dither is performed.

     It's possible other transate values will be added.

errdiff
     The type of error diffusion dither to perform.  These values (except
     for custom) can also be used in tr_errdif.

    floyd
          Floyd-Steinberg dither

    jarvis
          Jarvis, Judice and Ninke dither

    stucki
          Stucki dither

    custom
          Custom.  If you use this you must also set errdiff_width,
          errdiff_height and errdiff_map.

errdiff_width
errdiff_height
errdiff_orig
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.

perturb
     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";
     }

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 red arc with a 'center' at (200, 100) and spans 10
degrees and the slice has a radius of 20. SEE section on BUGS.

   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.

Text rendering
--------------

   To create a font object you can use:

     $t1font = Imager::Font->new(file=>'pathtofont.pfb');
     $ttfont = Imager::Font->new(file=>'pathtofont.ttf');

   As is two types of font types are supported t1 postscript fonts and
truetype fonts.  You can see if they are supported in your binary with the
`%Imager::formats' hash.  It is possible to control other attributes the
font such as default color, size and anti aliasing.

     $blue = Imager::Color->new(10,10,255,0);
     $t1font = Imager::Font->new(file=>'pathtofont.pfb',
                                 color=>$blue,
                                 size=30);

   To draw text on images the string method of the images is used.  A font
must be passed to the method.

     $img=Imager->new();
     $img=read(file=>"test.jpg");
     $img->string(font=>$t1font,
                  text=>"Model-XYZ",
                  x=>0,
                  y=>40,
                  size=>40,
                  color=>$red);
     $img->write(file=>"testout.jpg");

   This would put a 40 pixel high text in the top left corner of an image.
If you measure the actuall pixels it varies since the fonts usually do
not use their full height.  It seems that the color and size can be
specified twice.  When a font is created only the actual font specified
matters.  It his however convenient to store default values in a font,
such as color and size.  If parameters are passed to the string function
they are used instead of the defaults stored in the font.

   If string() is called with the channel parameter then the color isn't
used and the font is drawn in only one channel.  This can be quite handy
to create overlays.  See the examples for tips about this.

   Sometimes it is necessary to know how much space a string takes before
rendering it.  The bounding_box() method of a font can be used for that.
examples:

     @bbox=$font->bounding_box(string=>"testing",size=>15);
     @bbox=$font->bounding_box(string=>"testing",size=>15,canon=>1);
     @bbox=$font->bounding_box(string=>"testing",size=>15,x=50,y=>20);

   The first example gets the so called glyph metrics.  First is the

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

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).

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).  The `$srcimage' must be a 4 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
     turbnoise
     autolevels      lsat(0.1) usat(0.1) skew(0)
     radnoise
     noise           amount(3) subtype(0)
     contrast        intensity
     hardinvert

   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.

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.

   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.

Infix expressions
     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.

Postfix expressions
     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.

sin(N), cos(N), atan2(y,x)
     Some basic trig functions.  They work in radians, so you can't just
     use the hue values.

distance(x1, y1, x2, y2)
     Find the distance between two points.  This is handy (along with
     atan2()) for producing circular effects.

sqrt(n)
     Find the square root.  I haven't had much use for this since adding
     the distance() function.

abs(n)
     Find the absolute value.

getp1(x,y), getp2(x,y), getp3(x, y)
     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.

value(c), hue(c), sat(c), hsv(h,s,v)
     Separates a colour value into it's value (brightness), hue (colour)
     and saturation elements.  Use hsv() to put them back together (after
     suitable manipulation).

red(c), green(c), blue(c), rgb(r,g,b)
     Separates a colour value into it's red, green and blue colours.  Use
     rgb(r,g,b) to put it back together.

int(n)
     Convert a value to an integer.  Uses a C int cast, so it may break on
     large values.

if(cond,ntrue,nfalse), if(cond,ctrue,cfalse)
     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.

&&, ||, not(n)
     Basic logical operators.

   A few examples:

rpnexpr=>'x 25 % 15 * y 35 % 10 * getp1 !pat x y getp1 !pix @pix sat 0.7 gt @pat @pix ifp'
     tiles a smaller version of the input image over itself where the
     colour has a saturation over 0.7.

rpnexpr=>'x 25 % 15 * y 35 % 10 * getp1 !pat y 360 / !rat x y getp1 1 @rat - pmult @pat @rat pmult padd'
     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.

rpnexpr=>'x y getp1 !pix @pix value 0.96 gt @pix sat 0.1 lt and 128 128 255 rgb @pix ifp'
     replace pixels that are white or almost white with a palish blue

rpnexpr=>'x 35 % 10 * y 45 % 8 * getp1 !pat x y getp1 !pix @pix sat 0.2 lt @pix value 0.9 gt and @pix @pat @pix value 2 / 0.5 + pmult ifp'
     Tiles the input image overitself where the image isn't white or almost
     white.

rpnexpr=>'x y 160 180 distance !d y 180 - x 160 - atan2 !a @d 10 / @a + 3.1416 2 * % !a2 @a2 180 * 3.1416 / 1 @a2 sin 1 + 2 / hsv'
     Produces a spiral.

rpnexpr=>'x y 160 180 distance !d y 180 - x 160 - atan2 !a @d 10 / @a + 3.1416 2 * % !a2 @a 180 * 3.1416 / 1 @a2 sin 1 + 2 / hsv'
     A spiral built on top of a colour wheel.

   For details on expression parsing see *Note Imager/Expr: Imager/Expr,.
For details on the virtual machine used to transform the images, see
`Imager::regmach.pod' in this node.

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=>'ppm',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.

BUGS
====

   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.

AUTHOR
======

   Arnar M. Hrafnkelsson, addi@umich.edu And a great deal of help from
others - see the README for a complete list.  =head1 SEE ALSO

   perl(1), Affix::Infix2Postfix(3).
http://www.eecs.umich.edu/~addi/perl/Imager/


