=head1 NAME

Prima::Image - Bitmap routines


   use Prima qw(Application);

   # create a new image from scratch
   my $i = Prima::Image-> new(
      width => 32,
      height => 32,
      type   => im::BW, # same as im::bpp1 | im::GrayScale

   # draw something
   $i-> begin_paint;
   $i-> color( cl::White);
   $i-> ellipse( 5, 5, 10, 10);
   $i-> end_paint;

   # mangle
   $i-> size( 64, 64);

   # file operations
   $i-> save('a.gif') or die "Error saving:$@\n";
   $i-> load('a.gif') or die "Error loading:$@\n";

   # draw on screen
   $::application-> begin_paint;

   # an image is drawn as specified by its palette
   $::application-> set( color => cl::Red, backColor => cl::Green);
   $::application-> put_image( 100, 100, $i);

   # a bitmap is drawn as specified by destination device colors
   $::application-> put_image( 200, 100, $i-> bitmap);


I<Prima::Image>, I<Prima::Icon> and I<Prima::DeviceBitmap> are classes for
bitmap handling, including file and graphic input and output. I<Prima::Image>
and I<Prima::DeviceBitmap> are descendants of I<Prima::Drawable> and represent
bitmaps, stored in memory.  I<Prima::Icon> is a descendant of I<Prima::Image>
and contains a transparency mask along with the regular data.

=head1 USAGE

Images usually are represented as a memory area, where pixel data are stored
row-wise. The Prima toolkit is no exception, however, it does not assume that
the GUI system uses the same memory format.  The implicit conversion routines
are called when I<Prima::Image> is about to be drawn onto the screen, for
example. The conversions are not always efficient, therefore the
I<Prima::DeviceBitmap> class is introduced to represent a bitmap, stored in the
system memory in the system pixel format. These two basic classes serve the
different needs, but can be easily converted to each other, with C<image> and
C<bitmap> methods. I<Prima::Image> is a more general bitmap representation,
capable of file and graphic input and output, plus it is supplied with number
of conversion and scaling functions. The I<Prima::DeviceBitmap> class has
almost none of additional functionality, and is targeted to efficient graphic
input and output.

Note: If you're looking for information how to display an image, this is not
the manual page. Look either at L<Prima::ImageViewer>, or use C<put_image> /
C<stretch_image> ( L<Prima::Drawable> ) inside your widget's onPaint.

=head2 Graphic input and output

As descendants of I<Prima::Drawable>, all I<Prima::Image>, I<Prima::Icon> and
I<Prima::DeviceBitmap> objects are subject to three-state painting mode -
normal ( disabled ), painting ( enabled ) and informational.
I<Prima::DeviceBitmap> is, however, exists only in the enabled state, and can
not be switched to the other two.

When an object enters the enabled state, it serves as a canvas, and all
I<Prima::Drawable> operations can be performed on it. When the object is back
to the disabled state, the graphic information is stored into the object
associated memory, in the pixel format, supported by the toolkit.  This
information can be visualized by using one of C<Prima::Drawable::put_image>
group methods. If the object enters the enabled state again, the graphic
information is presented as an initial state of a bitmap.

It must be noted, that if an implicit conversion takes place after an object
enters and before it leaves the enabled state, as it is with I<Prima::Image>
and I<Prima::Icon>, the bitmap is converted to the system pixel format. During
such conversion some information can be lost, due to down-sampling, and there
is no way to preserve the information. This does not happen with

Image objects can be drawn upon images, as well as on the screen and
L<Prima::Widget> objects. This operation is performed via one of
I<Prima::Drawable::put_image> group methods ( see L<Prima::Drawable>), and can
be called with the image object disregarding the paint state. The following
code illustrates the dualism of an image object, where it can serve both as a
drawing surface and as a drawing tool:

    my $a = Prima::Image-> create( width => 100, height => 100, type => im::RGB);
    $a-> begin_paint;
    $a-> clear;
    $a-> color( cl::Green);
    $a-> fill_ellipse( 50, 50, 30, 30);
    $a-> end_paint;
    $a-> rop( rop::XorPut);
    $a-> put_image( 10, 10, $a);
    $::application-> begin_paint;
    $::application-> put_image( 0, 0, $a);
    $::application-> end_paint;

It must be noted, that C<put_image>, C<stretch_image> and C<put_image_indirect>
are only painting methods that allow drawing on an image that is in its
paint-disabled state. Moreover, in such context they only allow C<Prima::Image>
descendants to be passed as a source image object. This functionality does not
imply that the image is internally switched to the paint-enabled state and
back; the painting is performed without switching and without interference with
the system's graphical layer.

Another special case is a 1-bit ( monochrome ) DeviceBitmap. When it is drawn
upon a drawable with bit depth greater than 1, the drawable's color and
backColor properties are used to reflect 1 and 0 bits, respectively. On a 1-bit
drawable this does not happen, and the color properties are not used.

=head2 File input and output

Depending on the toolkit configuration, images can be read and written in
different formats. This functionality in accessible via C<load()> and C<save()>
methods. L<Prima::image-load> is dedicated to the description of loading and
saving parameters, that can be passed to the methods, so they can handle
different aspects of file format-specific options, such as multi-frame
operations, auto conversion when a format does not support a particular pixel
format etc. In this document, C<load()> and C<save()> methods are illustrated
only in their basic, single-frame functionality. When called with no extra
parameters, these methods fail only if a disk I/O error occurred or an unknown
image format was used.

When an image is loaded, the old bitmap memory content is discarded,
and the image attributes are changed accordingly to the loaded image.
Along with these, an image palette is loaded, if available, and
a pixel format is assigned, closest or identical to the pixel format
in the image file.

=head2 Pixel formats

I<Prima::Image> supports a number of pixel formats, governed by the C<::type>
property. It is reflected by an integer value, a combination of C<im::XXX>
constants. The whole set of pixel formats is represented by colored formats,
like, 16-color, 256-color and 16M-color, and by gray-scale formats, mapped to C
data types - unsigned char, unsigned short, unsigned long, float and double.
The gray-scale formats are further subdivided to real-number formats and
complex-number format; the last ones are represented by two real values per
pixel, containing the real and the imaginary values.

I<Prima::Image> can also be initialized from other formats, that it does not
support, but can convert data from. Currently these are represented by a set of
permutations of 32-bit RGBA format, and 24-bit BGR format.  These formats can
only be used in conjunction with C<::data> property.

The conversions can be performed between any of the supported formats ( to do
so, C<::type> property is to be set-called ). An image of any of these formats
can be drawn on the screen, but if the system can not accept the pixel format (
as it is with non-integer or complex formats ), the bitmap data are implicitly
converted. The conversion does not change the data if the image is about to be
drawn; the conversion is performed only when the image is about to be served as
a drawing surface. If, by any reason, it is desired that the pixel format is
not to be changed, the C<::preserveType> property must be set to 1. It does not
prevent the conversion, but it detects if the image was implicitly converted
inside C<end_paint()> call, and reverts it to its previous pixel format.

There are situations, when pixel format must be changed together while
down-sampling the image. One of four down-sampling methods can be selected -
no halftoning, 8x8 ordered halftoning, error diffusion, and error diffusion
combined with optimized palette. These can be set to
the C<::conversion> property with one of C<ict::XXX> constants.
When there is no information loss, C<::conversion> property is not used.

Another special case of conversion is a conversion with a palette. The following

  $image-> type( im::bpp4);
  $image-> palette( $palette);


  $image-> palette( $palette);
  $image-> type( im::bpp4);

produce different results, but none of these takes into account eventual
palette remapping, because C<::palette> property does not change bitmap pixel
data, but overwrites palette information. A proper call syntax here would be

  $image-> set(
     palette => $palette,
     type    => im::bpp4,

This call produces also palette pixel mapping.  This syntax is most powerful
when conversion is set to those algorithms that can take in the account the
existing image pixels, to produce an optimized palette. These are
C<ict::Optimized> ( by default ) and C<ict::Posterization>. This syntax not only allows
remapping or downsampling to a predefined colors set, but also can be used to
limit palette size to a particular number, without knowing the actual values of
the final color palette. For example, for an 24-bit image,

  $image-> set( type => im::bpp8, palette => 32);

call would calculate colors in the image, compress them to an optimized palette of
32 cells and finally converts to a 8-bit format.

Instead of C<palette> property, C<colormap> can also be used.

=head2 Data access

The pixel values can be accessed in I<Prima::Drawable> style, via C<::pixel>
property. However, I<Prima::Image> introduces several helper functions,
for different aims. The C<::data> property is used to set or retrieve
a scalar representation of bitmap data. The data are expected to be lined
up to a 'line size' margin ( 4-byte boundary ), which is calculated as

  $lineSize = int(( $image->width * ( $image-> type & im::BPP) + 31) / 32) * 4;

or returned from the read-only property C<::lineSize>.

This is the line size for the data as lined up internally in memory, however
C<::data> should not necessarily should be aligned like this, and can be
accompanied with a write-only flag 'lineSize' if pixels are aligned differently:

  $image-> set( width => 1, height=> 2);
  $image-> type( im::RGB);
  $image-> set(
     data => 'RGB----RGB----',
     lineSize => 7,
  print $image-> data, "\n";

  output: RGB-RGB-

Internally, Prima contains images in memory so that the first scanline is
the farthest away from the memory start; this is consistent with general
Y-axis orientation in Prima drawable terminology, but might be inconvenient
when importing data organized otherwise. Another write-only boolean flag C<reverse>
can be set to 1 so data then are treated as if the first scanline of the image
is the closest to the start of data:

  $image-> set( width => 1, height=> 2, type => im::RGB);
  $image-> set(
     data => 'RGB-123-',
     reverse => 1,
  print $image-> data, "\n";

  output: RGB-123-

Although it is possible to perform all kinds of calculations and modification
with the pixels, returned by C<::data>, it is not advisable unless the speed
does not matter. Standalone PDL package with help of L<PDL::PrimaImage>
package, and Prima-derived IPA package provide routines for data and image
analysis.  Also, L<Prima::Image::Magick> connects L<ImageMagick> with Prima.
I<Prima::Image> itself provides only the simplest statistic information,
namely: lowest and highest pixel values, pixel sum, sum of square pixels, mean,
variance, and standard deviation.

=head2 Standalone usage

Some of image functionality can be used standalone, with all other parts of the
toolkit being uninitialized. The functionality is limited to loading and
saving files, and reading and writing pixels (outside begin_paint only).
All other calls are ignored. Example:

   my $i = Prima::Image->new( size => [5,5]);

This feature is useful in non-interactive programs, running in environments
with no GUI access, a cgi-script with no access to X11 display, for example.
Normally, Prima fails to start in such situations, but can be told not to
initialize its GUI part by explicitly operating system-dependent options. To do
so, invoke

  use Prima::noX11;

in the beginning of your program. See L<Prima::noX11> for more.

Generally the standalone methods support all the OS-specific functions
(i.e. color, region, etc), plus they support alpha blending
using C<rop> property and C<rop::alpha($rop, $src_alpha[, $dst_alpha]))> value.

See individual methods and properties in L<API> that support standalone usage,
and how they differ from system-dependent implementation.

=head2 Prima::Icon

I<Prima::Icon> inherits all properties of I<Prima::Image>, and it also provides
a 1-bit depth transparency mask.  This mask can also be loaded and saved into
image files, if the format supports a transparency information.

Similar to I<Prima::Image::data> property, I<Prima::Icon::mask> property
provides access to the binary mask data.  The mask can be updated
automatically, after an icon object was subject to painting, resizing, or other
destructive change.  The auxiliary properties C<::autoMasking> and
C<::maskColor>/C<::maskIndex> regulate  mask update procedure. For example, if
an icon was loaded with the color ( vs. bitmap ) transparency information, the
binary mask will be generated anyway, but it will be also recorded that a
particular color serves as a transparent indicator, so eventual conversions can
rely on the color value, instead of the mask bitmap.

If an icon is drawn upon a graphic canvas, the image output is constrained to
the mask. On raster displays it is typically simulated by a combination of and-
and xor- operation modes, therefore attempts to put an icon with C<::rop>,
different from C<rop::CopyPut>, usually fail.

=head2 Layering

The term I<layered window> is borrowed from Windows world, and means a window
with transparency. In Prima, the property L<layered> is used to select this
functionality. The call to C<< $::application->get_system_value(sv::LayeredWidgets) >>
can check whether this functionality is available; if not, the property is ignored.
By default, widgets can not use layering.

A layered drawable uses an extra alpha channel to designate the transparency of
the widget. Drawing on widgets will also look different - for example, drawing
with black color will make the black pixels fully transparent, while other
colors will blend with the underlying background, but never in full. Prima
provides no functions to draw with alpha effects, and scarce image functions to
address the alpha surfaces. Drawing lines, text, etc with blending is delegated
to L<Prima::Cairo> which is a separate module. Prima only provides alpha
surfaces and bitmaps with an additional alpha channel to draw upon. However,
C<put_image> / C<stretch_image> functions can operate on surfaces with alpha as
source and destination drawables. To address the alpha channel on a drawable with
Prima, one has to send either an C<Prima::Icon> with C<maskType(im::bpp8)>, or
a layered C<DeviceBitmap> to these functions.

The corresponding C<Prima::DeviceBitmap> type is C<dbt::Layered>, and is fully
compatible with layered widgets in the same fashion as C<DeviceBitmap> with
type C<dbt::Pixmap> is fully compatible with normal widgets. One of ways to
put a constant alpha value over a rectangle is this, for example:

   my $a = Prima::Icon->new(
       width    => 1,
       height   => 1,
       type     => im::RGB,
       maskType => im::bpp8,
       data     => "\0\0\0",
       mask     => chr( $constant_alpha ),
   $drawable-> stretch_image( 0, 0, 100, 100, $a, rop::SrcOver );

If displaying a picture with pre-existing alpha channel, you'll need to call
L<premultiply_alpha>, because picture renderer assumes that pixel values are premultiplied.

Even though addressing alpha values of pixels when drawing on layered surfaces is not straighforward,
the conversion between images and device bitmaps fully supports alpha pixels. This means that:

* When drawing on an icon with 8-bit alpha channel (I<argb> icon), any changes to alpha
values of pixels will be transferred back to the mask property after C<end_paint>

* Calls to C<icon> function on DeviceBitmap with type C<dbt::Layered> produce identical
argb icons. Calls to C<bitmap> on argb icos produce identical layered device bitmaps.

* Putting argb icons and layered device bitmap on other drawables yields identical

Putting of argb source surfaces can be only used with two rops, C<rop::SrcOver>
(default) and C<rop::SrcCopy>. The former produces blending effect, while the
latter copies alpha bits over to the destination surface. Prima internal
implementation of C<put_image> and C<stretch_image> functions extends the
allowed set of rops when operating on images outside the begin_paint/end_paint
brackets. These rops support 12 Porter-Duff operators and flags to specify
constant alpha values to override the existing alpha channel, if any.  See more
in L<Prima::Drawable/Raster operations>.

Caveats: In Windows, mouse events will not be delivered to the layered widget
if the pixel under the mouse pointer is fully transparent.

See also: F<examples/layered.pl>.

=head1 API

=head2 Prima::Image properties


=item colormap @PALETTE

A color palette, used for representing 1, 4, and 8-bit bitmaps, when an image
object is to be visualized. @PALETTE contains individual colors component
triplets, in RGB format. For example, black-and-white monochrome image may
contain colormap as C<0,0xffffff>.

See also C<palette>.

=item conversion TYPE

Selects the type of dithering algorithm to be used for pixel down-sampling.
TYPE is one of C<ict::XXX> constants:

   ict::None            - no dithering, with static palette or palette optimized by source palette
   ict::Posterization   - no dithering, with optimized palette by source pixels
   ict::Ordered         - fast 8x8 ordered halftone dithering with static palette
   ict::ErrorDiffusion  - error diffusion dithering with static palette
   ict::Optimized       - error diffusion dithering with optimized palette

As an example, if a 4x4 color image with every pixel set to RGB(32,32,32),
converted to a 1-bit image, the following results occur:

   ict::None, ict::Posterization:
     [ 0 0 0 0 ]
     [ 0 0 0 0 ]
     [ 0 0 0 0 ]
     [ 0 0 0 0 ]

     [ 0 0 0 0 ]
     [ 0 0 1 0 ]
     [ 0 0 0 0 ]
     [ 1 0 0 0 ]

   ict::ErrorDiffusion, ict::Ordered:
     [ 0 0 1 0 ]
     [ 0 0 0 1 ]
     [ 0 0 0 0 ]
     [ 0 0 0 0 ]

Values of these constants are made from L<Prima::Const/ictp::> and L<Prima::Const/ictd::> constansts.

=for podview <img src="conversions.gif">

=for html <p><img src="https://raw.githubusercontent.com/dk/Prima/master/pod/Prima/conversions.gif">

=item data SCALAR

Provides access to the bitmap data. On get-call, returns all bitmap pixels,
aligned to 4-byte boundary. On set-call, stores the provided data with same
alignment. The alignment can be altered by submitting 'lineSize' write-only
flag to set call; the ordering of scan lines can be altered by setting
'reverse' write-only flag ( see L<Data access> ).

=item height INTEGER

Manages the vertical dimension of the image data.
On set-call, the image data are changed accordingly to the new height,
and depending on C<::vScaling> property,
the pixel values are either scaled or truncated.

=item lineSize INTEGER

A read-only property, returning the length of an image row in bytes, as
represented internally in memory. Data returned by C<::data> property are
aligned with C<::lineSize> bytes per row, and setting C<::data> expects data
aligned with this value, unless C<lineSize> is set together with C<data> to
indicate another alignment. See L<Data access> for more.

=item mean

Returns mean value of pixels.
Mean value is C<::sum> of pixel values, divided by number of pixels.

=item palette [ @PALETTE ]

A color palette, used for representing 1, 4, and 8-bit bitmaps, when an image
object is to be visualized. @PALETTE contains individual color component
triplets, in BGR format. For example, black-and-white monochrome image may
contain palette as C<[0,0,0,255,255,255]>.

See also C<colormap>.

=item pixel ( X_OFFSET, Y_OFFSET ) PIXEL

Provides per-pixel access to the image data when image object is in disabled
paint state.

Pixel values for grayscale 1- and 4- bit images are treated specifically, such
that like 8-bit function, values cover range between 0 and 255. F.ex. pixel
values for grayscale 1 bit images are 0 and 255, not 0 and 1.

In paint state same as C<Prima::Drawable::pixel>.

=item preserveType BOOLEAN

If 1, reverts the image type to its old value if an
implicit conversion was called during C<end_paint()>.

=item rangeHi

Returns maximum pixel value in the image data.

=item rangeLo

Returns minimum pixel value in the image data.

=item scaling INT

Declares the scaling strategy when image is resized.  Strategies C<ist::None>
through C<ist::Box> are very fast scalers, others not so.

Can be one of C<ist:::XXX> constants:

  ist::None      - image will be either stripped (when downsizing)
                   or padded (when upsizing) with zeros
  ist::Box       - image will be scaled using simple box transform
  ist::BoxX      - columns will behave same as in ist::None,
                   rows will behave same as in ist::Box
  ist::BoxY      - rows will behave same as in ist::None,
                   columns will behave same as in ist::Box
  ist::Triangle  - bilinear interpolation
  ist::Quadratic - 2rd order (quadratic) B-Spline approximation of Gaussian
  ist::Sinc      - sine function
  ist::Hermite   - B-Spline interpolation
  ist::Cubic     - 3rd order (cubic) B-Spline approximation of Gaussian
  ist::Gaussian  - Gaussian transform with gamma=0.5

=for podview <img src="scalings.gif">

=for html <p><img src="https://raw.githubusercontent.com/dk/Prima/master/pod/Prima/scalings.gif">

Note: Resampling scaling algorithms (those greater than C<ist::Box>), when applied to Icons with 1-bit
icon mask, will silently convert the mask in 8-bit and apply the same scaling algorithm to it. This
will have great smoothing effect on mask edges if the system supports ARGB layering (see L<"Layering"> ).

=item size WIDTH, HEIGHT

Manages dimensions of the image. On set-call,
the image data are changed accordingly to the new dimensions,
and depending on C<::scaling> property,
the pixel values are either scaled or truncated.

=item stats ( INDEX ) VALUE

Returns one of calculated values, that correspond to INDEX, which is one
of the following C<is::XXX> constants:

   is::RangeLo  - minimum pixel value
   is::RangeHi  - maximum pixel value
   is::Mean     - mean value
   is::Variance - variance
   is::StdDev   - standard deviation
   is::Sum      - sum of pixel values
   is::Sum2     - sum of squares of pixel values

The values are re-calculated on request and cached.
On set-call VALUE is stored in the cache, and is returned on next get-call.
The cached values are discarded every time the image data changes.

These values are also accessible via set of alias
properties: C<::rangeLo>, C<::rangeHi>, C<::mean>, C<::variance>,
C<::stdDev>, C<::sum>, C<::sum2>.

=item stdDev

Returns standard deviation of the image data.
Standard deviation is the square root of C<::variance>.

=item sum

Returns sum of pixel values of the image data

=item sum2

Returns sum of squares of pixel values of the image data

=item type TYPE

Governs the image pixel format type. TYPE is a combination
of C<im::XXX> constants. The constants are collected in groups:

Bit-depth constants provide size of pixel is bits. Their actual
value is same as number of bits, so C<im::bpp1> value is 1,
C<im::bpp4> - 4, etc. The valid constants represent bit depths
from 1 to 128:


The following values designate the pixel format category:


Value of C<im::Color> is 0, whereas other category constants
represented by unique bit value, so combination of
C<im::RealNumber> and C<im::ComplexNumber> is possible.

There also several mnemonic constants defined:

   im::Mono          - im::bpp1
   im::BW            - im::bpp1 | im::GrayScale
   im::16            - im::bpp4
   im::Nibble        - im::bpp4
   im::256           - im::bpp8
   im::RGB           - im::bpp24
   im::Triple        - im::bpp24
   im::Byte          - gray 8-bit unsigned integer
   im::Short         - gray 16-bit unsigned integer
   im::Long          - gray 32-bit unsigned integer
   im::Float         - float
   im::Double        - double
   im::Complex       - dual float
   im::DComplex      - dual double
   im::TrigComplex   - dual float
   im::TrigDComplex  - dual double

Bit depths of float- and double- derived pixel formats
depend on a platform.

The groups can be masked out with the mask values:

   im::BPP      - bit depth constants
   im::Category - category constants
   im::FMT      - extra format constants

The extra formats are the pixel formats, not supported by C<::type>,
but recognized within the combined set-call, like

   $image-> set(
      type => im::fmtBGRI,
      data => 'BGR-BGR-',

The data, supplied with the extra image format specification will
be converted to the closest supported format. Currently, the following
extra pixel formats are recognized:


=item variance

Returns variance of pixel values of the image data.
Variance is C<::sum2>, divided by number of pixels
minus square of C<::sum> of pixel values.

=item width INTEGER

Manages the horizontal dimension of the image data.
On set-call, the image data are changed accordingly to the new width,
and depending on C<::scaling> property,
the pixel values are either scaled or truncated.


=head2 Prima::Icon properties


=item autoMasking TYPE

Selects whether the mask information should be updated
automatically with C<::data> change or not. Every
C<::data> change is mirrored in C<::mask>, using TYPE,
one of C<am::XXX> constants:

   am::None           - no mask update performed
   am::MaskColor      - mask update based on ::maskColor property
   am::MaskIndex      - mask update based on ::maskIndex property
   am::Auto           - mask update based on corner pixel values

The C<::maskColor> color value is used as a transparent color if
TYPE is C<am::MaskColor>. The transparency mask generation algorithm,
turned on by C<am::Auto> checks corner pixel values, assuming that
majority of the corner pixels represents a transparent color. Once
such color is found, the mask is generated as in C<am::MaskColor>

C<::maskIndex> is the same as C<::maskColor>, except that it points
to a specific color index in the palette.

When image C<::data> is stretched, C<::mask> is stretched accordingly,
disregarding the C<::autoMasking> value.

=item mask SCALAR

Provides access to the transparency bitmap. On get-call, returns
all bitmap pixels, aligned to 4-byte boundary in 1-bit format. On set-call,
stores the provided transparency data with same alignment.

=item maskColor COLOR

When C<::autoMasking> set to C<am::MaskColor>, COLOR
is used as a transparency value.

=item maskIndex INDEX

When C<::autoMasking> set to C<am::MaskIndex>, INDEXth
color in teh current palette is used as a transparency value.

=item maskType INTEGER

Is either C<im::bpp1> (1) or C<im::bpp8> (8). The latter can be used
as a layered (argb) source surface to draw with blending effect.


=head2 Prima::DeviceBitmap properties


=item type INTEGER

A read-only property, that can only be set during creation,
reflects whether the system bitmap is black-and-white 1-bit (C<dbt::Bitmap>),
is colored and compatible with widgets (C<dbt::Pixmap>), or is colored with alpha
channel and compatible with layered widgets (C<dbt::Layered>).

The color depth of a bitmap can be read via C<get_bpp()> method; monochrome
bitmaps always have bit depth of 1, layered bitmaps have bit depth of 32.


=head2 Prima::Image methods


=item bar X1, Y1, X2, Y2

Outside the paint state uses owen implementation for drawing a rectangular shape.
The following properties are respected: C<color>, C<backColor>, C<rop>,
C<rop2>, C<fillPattern>, C<fillPatternOffset>, C<region>. C<rop2> accepts
either C<rop::CopyPut> or C<rop::NoOper> values, to produce either opaque or
transparent fill pattern application.

Inside the paint state is identical to C<Drawable::bar>.

=item bitmap

Returns newly created I<Prima::DeviceBitmap> instance,
with the image dimensions and with the bitmap pixel
values copied to.

=item clear [X1, Y1, X2, Y2]

Same as C<Drawable::clear> but can be used also outside of the paint state.

=item clone %properties

Creates a copy of the image and applies C<%properties>. An easy way to create
a down-sampled copy, for example.

=item codecs

Returns array of hashes, each describing the supported image
format. If the array is empty, the toolkit was set up so
it can not load and save images.

See L<Prima::image-load> for details.

This method can be called without object instance.

=item dup

Returns a duplicate of the object, a newly created I<Prima::Image>, with all
information copied to it. Does not preserve graphical properties (color etc).


Returns a newly created image object with WIDTH and HEIGHT dimensions,
initialized with pixel data from X_OFFSET and Y_OFFSET
in the bitmap.

=item fill_chord, fill_ellipse, fill_sector, flood_fill

Same as C<Drawable::> functions but can be used also outside of the paint state.

=item get_bpp

Returns the bit depth of the pixel format. Same as C<::type & im::BPP>.

=item get_handle

Returns a system handle for an image object.


Loads image from file FILENAME or stream FILEGLOB into an object, and returns the success flag.
The semantics of C<load()> is extensive, and can be influenced by
PARAMETERS hash. C<load()> can be called either in a context of an existing object,
then a boolean success flag is returned, or in a class context, then a newly
created object ( or C<undef> ) is returned. If an error occurs, C<$@> variable
contains the error description string. These two invocation semantics are

   my $x = Prima::Image-> create();
   die "$@" unless $x-> load( ... );


   my $x = Prima::Image-> load( ... );
   die "$@" unless $x;

See L<Prima::image-load> for details.

NB! When loading from streams on win32, mind C<binmode>.

=item map COLOR

Performs iterative mapping of bitmap pixels, setting every pixel
to C<::color> property with respect to C<::rop> type if a pixel
equals to COLOR, and to C<::backColor> property with respect
to C<::rop2> type otherwise.

C<rop::NoOper> type can be used for color masking.


   width => 4, height => 1, data => [ 1, 2, 3, 4]
   color => 10, backColor => 20, rop => rop::CopyPut

   rop2 => rop::CopyPut
   input: map(2) output: [ 20, 10, 20, 20 ]

   rop2 => rop::NoOper
   input: map(2) output: [ 1, 10, 3, 4 ]

=item mirror VERTICAL

Mirrors the image depending on boolean flag VERTICAL

=item premultiply_alpha CONSTANT_OR_IMAGE

Applies premultiplication formula to each pixel

   pixel = pixel * alpha / 256

where alpha either is a constant, or a pixel value in an image

=item put_image, put_image_indirect, stretch_image

Same as C<Drawable::> functions but can be used also outside of the paint state.

Extends raster functionality to access alpha channel either using constant
alpha values or C<Prima::Icon> as sources. See explanation of C<rop::>
constants in L<Prima::Drawable/Raster operations>.


Performs linear scaling of gray pixel values from range (SRC_LOW - SRC_HIGH)
to range (DEST_LOW - DEST_HIGH). Can be used to visualize
gray non-8 bit pixel values, by the code:

   $image-> resample( $image-> rangeLo, $image-> rangeHi, 0, 255);

=item rotate DEGREES

Rotates the image. Where the angle is 90, 180, or 270 degrees, fast pixel
flipping is used, otherwise fast Paeth rotation is used.  Eventual resampling
can be controlled by C<scaling> property ( probably not worth it for functions
with support of more than 1 pixel).

Resulting images can be 1 pixel too wide due to horizontal shearing applied
twice, where in worst cases 1 pixel from the original image can take 3
horizontal pixels on the result.


Stores image data into image file FILENAME or stream FILEGLOB, and returns the success flag.
The semantics of C<save()> is extensive, and can be influenced by
PARAMETERS hash. If error occurs, C<$@> variable
contains error description string.

Note that when saving to a stream, C<codecID> must be explicitly given in C<%PARAMETERS>.

See L<Prima::image-load> for details.

NB! When saving to streams on win32, mind C<binmode>.

=item shear X, Y

Applies shearing to the image. If the shearing is needed only for one axis, set
shear factor for the other one to zero.

=item to_region

Creates a new L<Prima::Region> object with the image as the data source.

=item transform @MATRIX

Applies generic 2D transform matrix to the image, where matrix is 4 numbers.

Tries first to split matrix into series of shear and scale transforms using LDU
decomposition; if an interim image needs to be too large, fails and returns

Rotation matrices can be applied too, however, when angles are close to 90 and
270, either interim images become too big, or defects introduced by shearing
become too visible. Therefore the method specifically detects for rotation
cases, and uses Paeth rotation algorithm instead, which yields better results.
Also, if the angle is detected to be 90, 180, or 270 degrees, fast pixel
flipping is used.

Eventual resampling can be controlled by C<scaling> property.

=item ui_scale %OPTIONS

Resizes the image with smooth scaling. Understands C<zoom> and C<scaling>
options. The C<zoom> default value is the one in C<< $::application->uiScaling >>,
the C<scaling> default value is C<ist::Quadratic> .

See also: L<Application/uiScaling>


=head2 Prima::Image events

C<Prima::Image>-specific events occur only from inside L<load> call, to report
image loading progress. Not all codecs (currently JPEG,PNG,TIFF only) are able
to report the progress to the caller. See L<Prima::image-load/"Loading with
progress indicator"> for details, L<Prima::ImageViewer/watch_load_progress> and
L<Prima::Dialog::ImageDialog/load> for suggested use.


=item HeaderReady EXTRAS

Called whenever image header is read, and image dimensions and pixel type
is changed accordingly to accomodate image data.

C<EXTRAS> is the hash to be stored later in C<{extras}> key on the object.

=item DataReady X, Y, WIDTH, HEIGHT

Called whenever image data that cover area designated by X,Y,WIDTH,HEIGHT
is acquired. Use C<load> option C<eventDelay> to limit the rate of C<DataReady>


=head2 Prima::Icon methods


=item alpha ALPHA <X1, Y1, X2, Y2>

Same as C<Drawable::alpha> but can be used also outside of the paint state.

=item combine DATA, MASK

Copies information from DATA and MASK images into C<::data>
and C<::mask> property. DATA and MASK are expected to be images
of same dimension.

=item create_combined DATA, MASK

Same as C<combine>, but to be called as constructor.

=item image %opt

Renders icon graphics on a newly created I<Prima::Image> object instance
upon black background.  If C<$opt{background}> is given, it is used instead.

=item premultiply_alpha CONSTANT_OR_IMAGE = undef

Applies premultiplication formula to each pixel

   pixel = pixel * alpha / 256

where alpha is the corresponding alpha value for each coordinate.
Only applicable when C<maskType> is <im::bpp8>.

=item split

Returns two new I<Prima::Image> objects of same dimension.
Pixels in the first is are duplicated from C<::data> storage,
in the second - from C<::mask> storage.

=item ui_scale %OPTIONS

Same as C<ui_scale> from C<Prima::Image>, but with few exceptions: It tries to
use C<ist::Quadratic> only when the system supports ARGB layering. Otherwise,
falls back on C<ist::Box> scaling algorithm, and also limits the zoom factor to
integers (2x, 3x etc) only, because when displayed, the smooth-scaled color
plane will not match mask plane downgraded to 0/1 mask, and because box-scaling
with non-integer zooms looks ugly.


=head2 Prima::DeviceBitmap methods


=item dup

Returns a duplicate of the object, a newly created I<Prima::DeviceBitmap>, with all
information copied to it. Does not preserve graphical properties (color etc).

=item icon

Returns a newly created I<Prima::Icon> object instance, with the
pixel information copied from the object. If the bitmap is layered,
returns icons with maskType set to C<im::bpp8>.

=item image

Returns a newly created I<Prima::Image> object instance, with the
pixel information copied from the object.

=item get_handle

Returns a system handle for a system bitmap object.


=head1 AUTHOR

Dmitry Karasik, E<lt>dmitry@karasik.eu.orgE<gt>.

=head1 SEE ALSO

L<Prima>, L<Prima::Drawable>, L<Prima::image-load>, L<Prima::codecs>.

L<PDL>, L<PDL::PrimaImage>, L<IPA>

L<ImageMagick>, L<Prima::Image::Magick>