1=head1 NAME
2
3Prima::Image - Bitmap routines
4
5=head1 SYNOPSIS
6
7   use Prima qw(Application);
8
9   # create a new image from scratch
10   my $i = Prima::Image-> new(
11      width => 32,
12      height => 32,
13      type   => im::BW, # same as im::bpp1 | im::GrayScale
14   );
15
16   # draw something
17   $i-> begin_paint;
18   $i-> color( cl::White);
19   $i-> ellipse( 5, 5, 10, 10);
20   $i-> end_paint;
21
22   # mangle
23   $i-> size( 64, 64);
24
25   # file operations
26   $i-> save('a.gif') or die "Error saving:$@\n";
27   $i-> load('a.gif') or die "Error loading:$@\n";
28
29   # draw on screen
30   $::application-> begin_paint;
31
32   # an image is drawn as specified by its palette
33   $::application-> put_image( 100, 100, $i);
34
35   # a bitmap is drawn as specified by destination device colors
36   $::application-> set( color => cl::Red, backColor => cl::Green);
37   $::application-> put_image( 200, 100, $i-> bitmap);
38
39
40=head1 DESCRIPTION
41
42I<Prima::Image>, I<Prima::Icon> and I<Prima::DeviceBitmap> are classes for
43bitmap handling, including file and graphic input and output. I<Prima::Image>
44and I<Prima::DeviceBitmap> are descendants of I<Prima::Drawable> and represent
45bitmaps, stored in memory.  I<Prima::Icon> is a descendant of I<Prima::Image>
46and contains a transparency mask along with the regular data.
47
48=head1 USAGE
49
50Images usually are represented as a memory area, where pixel data are stored
51row-wise. The Prima toolkit is no exception, however, it does not assume that
52the GUI system uses the same memory format.  The implicit conversion routines
53are called when I<Prima::Image> is about to be drawn onto the screen, for
54example. The conversions are not always efficient, therefore the
55I<Prima::DeviceBitmap> class is introduced to represent a bitmap, stored in the
56system memory in the system pixel format. These two basic classes serve the
57different needs, but can be easily converted to each other, with C<image> and
58C<bitmap> methods. I<Prima::Image> is a more general bitmap representation,
59capable of file and graphic input and output, plus it is supplied with number
60of conversion and scaling functions. The I<Prima::DeviceBitmap> class has
61almost none of additional functionality, and is targeted to efficient graphic
62input and output.
63
64Note: If you're looking for information how to display an image, this is not
65the manual page. Look either at L<Prima::ImageViewer>, or use C<put_image> /
66C<stretch_image> ( L<Prima::Drawable> ) inside your widget's onPaint.
67
68=head2 Graphic input and output
69
70As descendants of I<Prima::Drawable>, all I<Prima::Image>, I<Prima::Icon> and
71I<Prima::DeviceBitmap> objects are subject to three-state painting mode -
72normal ( disabled ), painting ( enabled ) and informational.
73I<Prima::DeviceBitmap> is, however, exists only in the enabled state, and can
74not be switched to the other two.
75
76When an object enters the enabled state, it serves as a canvas, and all
77I<Prima::Drawable> operations can be performed on it. When the object is back
78to the disabled state, the graphic information is stored into the object
79associated memory, in the pixel format, supported by the toolkit.  This
80information can be visualized by using one of C<Prima::Drawable::put_image>
81group methods. If the object enters the enabled state again, the graphic
82information is presented as an initial state of a bitmap.
83
84It must be noted, that if an implicit conversion takes place after an object
85enters and before it leaves the enabled state, as it is with I<Prima::Image>
86and I<Prima::Icon>, the bitmap is converted to the system pixel format. During
87such conversion some information can be lost, due to down-sampling, and there
88is no way to preserve the information. This does not happen with
89I<Prima::DeviceBitmap>.
90
91Image objects can be drawn upon images, as well as on the screen and
92L<Prima::Widget> objects. This operation is performed via one of
93I<Prima::Drawable::put_image> group methods ( see L<Prima::Drawable>), and can
94be called with the image object disregarding the paint state. The following
95code illustrates the dualism of an image object, where it can serve both as a
96drawing surface and as a drawing tool:
97
98    my $a = Prima::Image-> create( width => 100, height => 100, type => im::RGB);
99    $a-> begin_paint;
100    $a-> clear;
101    $a-> color( cl::Green);
102    $a-> fill_ellipse( 50, 50, 30, 30);
103    $a-> end_paint;
104    $a-> rop( rop::XorPut);
105    $a-> put_image( 10, 10, $a);
106    $::application-> begin_paint;
107    $::application-> put_image( 0, 0, $a);
108    $::application-> end_paint;
109
110It must be noted, that C<put_image>, C<stretch_image> and C<put_image_indirect>
111only allow C<Prima::Image> descendants to be passed as a source image object.
112This functionality does not imply that the image is internally switched to the
113paint-enabled state and back; on the contrary, the painting is performed without switching and
114using only Prima's own code, without using the system's graphical layer.
115
116Another special case is a 1-bit ( monochrome ) DeviceBitmap. When it is drawn
117upon a drawable with bit depth greater than 1, the drawable's color and
118backColor properties are used to reflect 1 and 0 bits, respectively. On a 1-bit
119drawable this does not happen, and the color properties are not used.
120
121=head2 File input and output
122
123Depending on the toolkit configuration, images can be read and written in
124different formats. This functionality in accessible via C<load()> and C<save()>
125methods. L<Prima::image-load> is dedicated to the description of loading and
126saving parameters, that can be passed to the methods, so they can handle
127different aspects of file format-specific options, such as multi-frame
128operations, auto conversion when a format does not support a particular pixel
129format etc. In this document, C<load()> and C<save()> methods are illustrated
130only in their basic, single-frame functionality. When called with no extra
131parameters, these methods fail only if a disk I/O error occurred or an unknown
132image format was used.
133
134When an image is loaded, the old bitmap memory content is discarded,
135and the image attributes are changed accordingly to the loaded image.
136Along with these, an image palette is loaded, if available, and
137a pixel format is assigned, closest or identical to the pixel format
138in the image file.
139
140=head2 Pixel formats
141
142I<Prima::Image> supports a number of pixel formats, governed by the C<::type>
143property. It is reflected by an integer value, a combination of C<im::XXX>
144constants. The whole set of pixel formats is represented by colored formats,
145like, 16-color, 256-color and 16M-color, and by gray-scale formats, mapped to C
146data types - unsigned char, unsigned short, unsigned long, float and double.
147The gray-scale formats are further subdivided to real-number formats and
148complex-number format; the last ones are represented by two real values per
149pixel, containing the real and the imaginary values.
150
151I<Prima::Image> can also be initialized from other formats, that it does not
152support, but can convert data from. Currently these are represented by a set of
153permutations of 32-bit RGBA format, and 24-bit BGR format.  These formats can
154only be used in conjunction with C<::data> property.
155
156The conversions can be performed between any of the supported formats ( to do
157so, C<::type> property is to be set-called ). An image of any of these formats
158can be drawn on the screen, but if the system can not accept the pixel format (
159as it is with non-integer or complex formats ), the bitmap data are implicitly
160converted. The conversion does not change the data if the image is about to be
161drawn; the conversion is performed only when the image is about to be served as
162a drawing surface. If, by any reason, it is desired that the pixel format is
163not to be changed, the C<::preserveType> property must be set to 1. It does not
164prevent the conversion, but it detects if the image was implicitly converted
165inside C<end_paint()> call, and reverts it to its previous pixel format.
166
167There are situations, when pixel format must be changed together while
168down-sampling the image. One of four down-sampling methods can be selected -
169no halftoning, 8x8 ordered halftoning, error diffusion, and error diffusion
170combined with optimized palette. These can be set to
171the C<::conversion> property with one of C<ict::XXX> constants.
172When there is no information loss, C<::conversion> property is not used.
173
174Another special case of conversion is a conversion with a palette. The following
175calls,
176
177  $image-> type( im::bpp4);
178  $image-> palette( $palette);
179
180and
181
182  $image-> palette( $palette);
183  $image-> type( im::bpp4);
184
185produce different results, but none of these takes into account eventual
186palette remapping, because C<::palette> property does not change bitmap pixel
187data, but overwrites palette information. A proper call syntax here would be
188
189  $image-> set(
190     palette => $palette,
191     type    => im::bpp4,
192  );
193
194This call produces also palette pixel mapping.  This syntax is most powerful
195when conversion is set to those algorithms that can take in the account the
196existing image pixels, to produce an optimized palette. These are
197C<ict::Optimized> ( by default ) and C<ict::Posterization>. This syntax not only allows
198remapping or downsampling to a predefined colors set, but also can be used to
199limit palette size to a particular number, without knowing the actual values of
200the final color palette. For example, for an 24-bit image,
201
202  $image-> set( type => im::bpp8, palette => 32);
203
204call would calculate colors in the image, compress them to an optimized palette of
20532 cells and finally converts to a 8-bit format.
206
207Instead of C<palette> property, C<colormap> can also be used.
208
209=head2 Data access
210
211The pixel values can be accessed in I<Prima::Drawable> style, via C<::pixel>
212property. However, I<Prima::Image> introduces several helper functions on its own.
213
214The C<::data> property is used to set or retrieve a scalar representation of
215bitmap data. The data are expected to be lined up to a 'line size' margin (
2164-byte boundary ), which is calculated as
217
218  $lineSize = int(( $image->width * ( $image-> type & im::BPP) + 31) / 32) * 4;
219
220or returned from the read-only property C<::lineSize>.
221
222This is the line size for the data as lined up internally in memory, however
223C<::data> should not necessarily should be aligned like this, and can be
224accompanied with a write-only flag 'lineSize' if pixels are aligned differently:
225
226  $image-> set( width => 1, height=> 2);
227  $image-> type( im::RGB);
228  $image-> set(
229     data => 'RGB----RGB----',
230     lineSize => 7,
231  );
232  print $image-> data, "\n";
233
234  output: RGB-RGB-
235
236Internally, Prima contains images in memory so that the first scanline is
237the farthest away from the memory start; this is consistent with general
238Y-axis orientation in Prima drawable terminology, but might be inconvenient
239when importing data organized otherwise. Another write-only boolean flag C<reverse>
240can be set to 1 so data then are treated as if the first scanline of the image
241is the closest to the start of data:
242
243  $image-> set( width => 1, height=> 2, type => im::RGB);
244  $image-> set(
245     data => 'RGB-123-',
246     reverse => 1,
247  );
248  print $image-> data, "\n";
249
250  output: RGB-123-
251
252
253Although it is possible to perform all kinds of calculations and modification
254with the pixels, returned by C<::data>, it is not advisable unless the speed
255does not matter. Standalone PDL package with help of L<PDL::PrimaImage>
256package, and Prima-derived IPA package provide routines for data and image
257analysis.  Also, L<Prima::Image::Magick> connects L<ImageMagick> with Prima.
258I<Prima::Image> itself provides only the simplest statistic information,
259namely: lowest and highest pixel values, pixel sum, sum of square pixels, mean,
260variance, and standard deviation.
261
262=head2 Standalone usage
263
264Some of image functionality can be used standalone, with all other parts of the
265toolkit being uninitialized. The functionality is limited to loading and
266saving files, and reading and writing pixels (outside begin_paint only).
267All other calls are ignored. Example:
268
269   my $i = Prima::Image->new( size => [5,5]);
270   $i->color(cl::Red);
271   $i->bar(0,0,$i->size);
272   $i->save('1.bmp');
273
274This feature is useful in non-interactive programs, running in environments
275with no GUI access, a cgi-script with no access to X11 display, for example.
276Normally, Prima fails to start in such situations, but can be told not to
277initialize its GUI part by explicitly operating system-dependent options. To do
278so, invoke
279
280  use Prima::noX11;
281
282in the beginning of your program. See L<Prima::noX11> for more.
283
284Generally the standalone methods support all the OS-specific functions (i.e.
285color, region, etc), plus the primitives and C<put_image> methods support
286drawing using Porter-Duff operators from C<rop> property (i e rop::SrcOver and
287above).
288
289See individual methods and properties in L<API> that support standalone usage,
290and how they differ from system-dependent implementation.
291
292=head2 Prima::Icon
293
294I<Prima::Icon> inherits all properties of I<Prima::Image>, and it also provides
295a transparency mask of either 1 or 8 bits.  This mask can also be loaded
296and saved into image files, if the format supports transparency information.
297
298Similar to I<Prima::Image::data> property, I<Prima::Icon::mask> property
299provides access to the binary mask data.  The mask can be updated
300automatically, after an icon object was subject to painting, resizing, or other
301destructive change.  The auxiliary properties C<::autoMasking> and
302C<::maskColor>/C<::maskIndex> regulate  mask update procedure. For example, if
303an icon was loaded with the color ( vs. bitmap ) transparency information, the
304binary mask will be generated anyway, but it will be also recorded that a
305particular color serves as a transparent indicator, so eventual conversions can
306rely on the color value, instead of the mask bitmap.
307
308If an icon is drawn upon a graphic canvas, the image output is constrained to
309the mask. On raster displays it is typically simulated by a combination of and-
310and xor- operation modes, therefore attempts to put an icon with C<::rop>,
311different from C<rop::CopyPut>, usually fail.
312
313=head2 Layering
314
315The term I<layered window> is borrowed from Windows world, and means a window
316with transparency. In Prima, the property L<layered> is used to select this
317functionality. The call to C<< $::application->get_system_value(sv::LayeredWidgets) >>
318can check whether this functionality is available; if not, the property is ignored.
319By default, widgets can not use layering.
320
321A layered drawable uses an extra alpha channel to designate the transparency.
322Drawing on widgets will also look different - for example, drawing
323with black color will make the black pixels fully transparent, while other
324colors will blend with the underlying background, but never in full. Prima
325provides graphics primitives to draw using alpha effects, and some image functions to
326address the alpha surfaces.
327
328C<put_image> / C<stretch_image> functions can operate on surfaces with alpha as
329source and destination drawables. To address the alpha channel on a drawable with
330Prima, one has to send either an C<Prima::Icon> with C<maskType(im::bpp8)>, or
331a layered C<DeviceBitmap> to these functions.
332
333The corresponding C<Prima::DeviceBitmap> type is C<dbt::Layered>, and is fully
334compatible with layered widgets in the same fashion as C<DeviceBitmap> with
335type C<dbt::Pixmap> is fully compatible with normal widgets. One of ways to
336put a constant alpha value over a rectangle is this, for example:
337
338   my $a = Prima::Icon->new(
339       width    => 1,
340       height   => 1,
341       type     => im::RGB,
342       maskType => im::bpp8,
343       data     => "\0\0\0",
344       mask     => chr( $constant_alpha ),
345   );
346   $drawable-> stretch_image( 0, 0, 100, 100, $a, rop::SrcOver );
347
348If displaying a picture with pre-existing alpha channel, you'll need to call
349L<premultiply_alpha>, because picture renderer assumes that pixel values are premultiplied.
350
351Even though addressing alpha values of pixels when drawing on layered surfaces is not straighforward,
352the conversion between images and device bitmaps fully supports alpha pixels. This means that:
353
354* When drawing on an icon with 8-bit alpha channel (I<argb> icon), any changes to alpha
355values of pixels will be transferred back to the mask property after C<end_paint>
356
357* Calls to C<icon> function on DeviceBitmap with type C<dbt::Layered> produce identical
358argb icons. Calls to C<bitmap> on argb icos produce identical layered device bitmaps.
359
360* Putting argb icons and layered device bitmap on other drawables yields identical
361results.
362
363Putting of argb source surfaces can be only used with two rops, C<rop::SrcOver>
364(default) and C<rop::SrcCopy>. The former produces blending effect, while the
365latter copies alpha bits over to the destination surface. Prima internal
366implementation of C<put_image> and C<stretch_image> functions extends the
367allowed set of rops when operating on images outside the begin_paint/end_paint
368brackets. These rops support 12 Porter-Duff operators, some more "photoshop"
369operators, and special flags to specify constant alpha values to override the
370existing alpha channel, if any.
371See more in L<Prima::Drawable/Raster operations>.
372
373Caveats: In Windows, mouse events will not be delivered to the layered widget
374if the pixel under the mouse pointer is fully transparent.
375
376See also: F<examples/layered.pl>.
377
378=head1 API
379
380=head2 Prima::Image properties
381
382=over
383
384=item colormap @PALETTE
385
386A color palette, used for representing 1, 4, and 8-bit bitmaps, when an image
387object is to be visualized. @PALETTE contains individual colors component
388triplets, in RGB format. For example, black-and-white monochrome image may
389contain colormap as C<0,0xffffff>.
390
391See also C<palette>.
392
393=item conversion TYPE
394
395Selects the type of dithering algorithm to be used for pixel down-sampling.
396TYPE is one of C<ict::XXX> constants:
397
398   ict::None            - no dithering, with static palette or palette optimized by source palette
399   ict::Posterization   - no dithering, with optimized palette by source pixels
400   ict::Ordered         - fast 8x8 ordered halftone dithering with static palette
401   ict::ErrorDiffusion  - error diffusion dithering with static palette
402   ict::Optimized       - error diffusion dithering with optimized palette
403
404As an example, if a 4x4 color image with every pixel set to RGB(32,32,32),
405converted to a 1-bit image, the following results occur:
406
407   ict::None, ict::Posterization:
408     [ 0 0 0 0 ]
409     [ 0 0 0 0 ]
410     [ 0 0 0 0 ]
411     [ 0 0 0 0 ]
412
413   ict::Ordered:
414     [ 0 0 0 0 ]
415     [ 0 0 1 0 ]
416     [ 0 0 0 0 ]
417     [ 1 0 0 0 ]
418
419   ict::ErrorDiffusion, ict::Ordered:
420     [ 0 0 1 0 ]
421     [ 0 0 0 1 ]
422     [ 0 0 0 0 ]
423     [ 0 0 0 0 ]
424
425Values of these constants are made from L<Prima::Const/ictp::> and L<Prima::Const/ictd::> constansts.
426
427=for podview <img src="conversions.gif">
428
429=for html <p><img src="https://raw.githubusercontent.com/dk/Prima/master/pod/Prima/conversions.gif">
430
431=item data SCALAR
432
433Provides access to the bitmap data. On get-call, returns all bitmap pixels,
434aligned to 4-byte boundary. On set-call, stores the provided data with same
435alignment. The alignment can be altered by submitting 'lineSize' write-only
436flag to set call; the ordering of scan lines can be altered by setting
437'reverse' write-only flag ( see L<Data access> ).
438
439=item height INTEGER
440
441Manages the vertical dimension of the image data.
442On set-call, the image data are changed accordingly to the new height,
443and depending on C<::vScaling> property,
444the pixel values are either scaled or truncated.
445
446=item lineSize INTEGER
447
448A read-only property, returning the length of an image row in bytes, as
449represented internally in memory. Data returned by C<::data> property are
450aligned with C<::lineSize> bytes per row, and setting C<::data> expects data
451aligned with this value, unless C<lineSize> is set together with C<data> to
452indicate another alignment. See L<Data access> for more.
453
454=item mean
455
456Returns mean value of pixels.
457Mean value is C<::sum> of pixel values, divided by number of pixels.
458
459=item palette [ @PALETTE ]
460
461A color palette, used for representing 1, 4, and 8-bit bitmaps, when an image
462object is to be visualized. @PALETTE contains individual color component
463triplets, in BGR format. For example, black-and-white monochrome image may
464contain palette as C<[0,0,0,255,255,255]>.
465
466See also C<colormap>.
467
468=item pixel ( X_OFFSET, Y_OFFSET ) PIXEL
469
470Provides per-pixel access to the image data when image object is in disabled
471paint state.
472
473Pixel values for grayscale 1- and 4- bit images are treated specifically, such
474that like 8-bit function, values cover range between 0 and 255. F.ex. pixel
475values for grayscale 1 bit images are 0 and 255, not 0 and 1.
476
477In paint state same as C<Prima::Drawable::pixel>.
478
479=item preserveType BOOLEAN
480
481If 1, reverts the image type to its old value if an
482implicit conversion was called during C<end_paint()>.
483
484=item rangeHi
485
486Returns maximum pixel value in the image data.
487
488=item rangeLo
489
490Returns minimum pixel value in the image data.
491
492=item scaling INT
493
494Declares the scaling strategy when image is resized.  Strategies C<ist::None>
495through C<ist::Box> are very fast scalers, others not so.
496
497Can be one of C<ist:::XXX> constants:
498
499  ist::None      - image will be either stripped (when downsizing)
500                   or padded (when upsizing) with zeros
501  ist::Box       - image will be scaled using simple box transform
502  ist::BoxX      - columns will behave same as in ist::None,
503                   rows will behave same as in ist::Box
504  ist::BoxY      - rows will behave same as in ist::None,
505                   columns will behave same as in ist::Box
506  ist::AND       - when row or columns is to be shrunk, leftover pixels
507                   will be AND-end together (for black on white)
508		   ( does not work for floating poing pixels )
509  ist::OR        - when row or columns is to be shrunk, leftover pixels
510                   will be OR-end together (for white on black)
511		   ( does not work for floating poing pixels )
512  ist::Triangle  - bilinear interpolation
513  ist::Quadratic - 2rd order (quadratic) B-Spline approximation of Gaussian
514  ist::Sinc      - sine function
515  ist::Hermite   - B-Spline interpolation
516  ist::Cubic     - 3rd order (cubic) B-Spline approximation of Gaussian
517  ist::Gaussian  - Gaussian transform with gamma=0.5
518
519=for podview <img src="scalings.gif">
520
521=for html <p><img src="https://raw.githubusercontent.com/dk/Prima/master/pod/Prima/scalings.gif">
522
523Note: Resampling scaling algorithms (those greater than C<ist::Box>), when applied to Icons with 1-bit
524icon mask, will silently convert the mask in 8-bit and apply the same scaling algorithm to it. This
525will have great smoothing effect on mask edges if the system supports ARGB layering (see L<"Layering"> ).
526
527=item size WIDTH, HEIGHT
528
529Manages dimensions of the image. On set-call,
530the image data are changed accordingly to the new dimensions,
531and depending on C<::scaling> property,
532the pixel values are either scaled or truncated.
533
534=item stats ( INDEX ) VALUE
535
536Returns one of calculated values, that correspond to INDEX, which is one
537of the following C<is::XXX> constants:
538
539   is::RangeLo  - minimum pixel value
540   is::RangeHi  - maximum pixel value
541   is::Mean     - mean value
542   is::Variance - variance
543   is::StdDev   - standard deviation
544   is::Sum      - sum of pixel values
545   is::Sum2     - sum of squares of pixel values
546
547The values are re-calculated on request and cached.
548On set-call VALUE is stored in the cache, and is returned on next get-call.
549The cached values are discarded every time the image data changes.
550
551These values are also accessible via set of alias
552properties: C<::rangeLo>, C<::rangeHi>, C<::mean>, C<::variance>,
553C<::stdDev>, C<::sum>, C<::sum2>.
554
555=item stdDev
556
557Returns standard deviation of the image data.
558Standard deviation is the square root of C<::variance>.
559
560=item sum
561
562Returns sum of pixel values of the image data
563
564=item sum2
565
566Returns sum of squares of pixel values of the image data
567
568=item type TYPE
569
570Governs the image pixel format type. TYPE is a combination
571of C<im::XXX> constants. The constants are collected in groups:
572
573Bit-depth constants provide size of pixel is bits. Their actual
574value is same as number of bits, so C<im::bpp1> value is 1,
575C<im::bpp4> - 4, etc. The valid constants represent bit depths
576from 1 to 128:
577
578   im::bpp1
579   im::bpp4
580   im::bpp8
581   im::bpp16
582   im::bpp24
583   im::bpp32
584   im::bpp64
585   im::bpp128
586
587The following values designate the pixel format category:
588
589   im::Color
590   im::GrayScale
591   im::RealNumber
592   im::ComplexNumber
593   im::TrigComplexNumber
594   im::SignedInt
595
596Value of C<im::Color> is 0, whereas other category constants
597represented by unique bit value, so combination of
598C<im::RealNumber> and C<im::ComplexNumber> is possible.
599
600There also several mnemonic constants defined:
601
602   im::Mono          - im::bpp1
603   im::BW            - im::bpp1 | im::GrayScale
604   im::16            - im::bpp4
605   im::Nibble        - im::bpp4
606   im::256           - im::bpp8
607   im::RGB           - im::bpp24
608   im::Triple        - im::bpp24
609   im::Byte          - gray 8-bit unsigned integer
610   im::Short         - gray 16-bit unsigned integer
611   im::Long          - gray 32-bit unsigned integer
612   im::Float         - float
613   im::Double        - double
614   im::Complex       - dual float
615   im::DComplex      - dual double
616   im::TrigComplex   - dual float
617   im::TrigDComplex  - dual double
618
619Bit depths of float- and double- derived pixel formats
620depend on a platform.
621
622The groups can be masked out with the mask values:
623
624   im::BPP      - bit depth constants
625   im::Category - category constants
626   im::FMT      - extra format constants
627
628The extra formats are the pixel formats, not supported by C<::type>,
629but recognized within the combined set-call, like
630
631   $image-> set(
632      type => im::fmtBGRI,
633      data => 'BGR-BGR-',
634   );
635
636The data, supplied with the extra image format specification will
637be converted to the closest supported format. Currently, the following
638extra pixel formats are recognized:
639
640   im::fmtBGR
641   im::fmtRGBI
642   im::fmtIRGB
643   im::fmtBGRI
644   im::fmtIBGR
645
646=item variance
647
648Returns variance of pixel values of the image data.
649Variance is C<::sum2>, divided by number of pixels
650minus square of C<::sum> of pixel values.
651
652=item width INTEGER
653
654Manages the horizontal dimension of the image data.
655On set-call, the image data are changed accordingly to the new width,
656and depending on C<::scaling> property,
657the pixel values are either scaled or truncated.
658
659=back
660
661=head2 Prima::Icon properties
662
663=over
664
665=item autoMasking TYPE
666
667Selects whether the mask information should be updated
668automatically with C<::data> change or not. Every
669C<::data> change is mirrored in C<::mask>, using TYPE,
670one of C<am::XXX> constants:
671
672   am::None           - no mask update performed
673   am::MaskColor      - mask update based on ::maskColor property
674   am::MaskIndex      - mask update based on ::maskIndex property
675   am::Auto           - mask update based on corner pixel values
676
677The C<::maskColor> color value is used as a transparent color if
678TYPE is C<am::MaskColor>. The transparency mask generation algorithm,
679turned on by C<am::Auto> checks corner pixel values, assuming that
680majority of the corner pixels represents a transparent color. Once
681such color is found, the mask is generated as in C<am::MaskColor>
682case.
683
684C<::maskIndex> is the same as C<::maskColor>, except that it points
685to a specific color index in the palette.
686
687When image C<::data> is stretched, C<::mask> is stretched accordingly,
688disregarding the C<::autoMasking> value.
689
690=item mask SCALAR
691
692Provides access to the transparency bitmap. On get-call, returns
693all bitmap pixels, aligned to 4-byte boundary in 1-bit format. On set-call,
694stores the provided transparency data with same alignment.
695
696=item maskColor COLOR
697
698When C<::autoMasking> set to C<am::MaskColor>, COLOR
699is used as a transparency value.
700
701=item maskIndex INDEX
702
703When C<::autoMasking> set to C<am::MaskIndex>, INDEXth
704color in teh current palette is used as a transparency value.
705
706=item maskType INTEGER
707
708Is either C<im::bpp1> (1) or C<im::bpp8> (8). The latter can be used
709as a layered (argb) source surface to draw with blending effect.
710
711=back
712
713=head2 Prima::DeviceBitmap properties
714
715=over
716
717=item type INTEGER
718
719A read-only property, that can only be set during creation,
720reflects whether the system bitmap is black-and-white 1-bit (C<dbt::Bitmap>),
721is colored and compatible with widgets (C<dbt::Pixmap>), or is colored with alpha
722channel and compatible with layered widgets (C<dbt::Layered>).
723
724The color depth of a bitmap can be read via C<get_bpp()> method; monochrome
725bitmaps always have bit depth of 1, layered bitmaps have bit depth of 32.
726
727=back
728
729=head2 Prima::Image methods
730
731=over
732
733=item bar X1, Y1, X2, Y2
734
735Outside the paint state uses owen implementation for drawing a rectangular shape.
736The following properties are respected: C<color>, C<backColor>, C<rop>,
737C<rop2>, C<fillPattern>, C<fillPatternOffset>, C<region>. C<rop2> accepts
738either C<rop::CopyPut> or C<rop::NoOper> values, to produce either opaque or
739transparent fill pattern application.
740
741Inside the paint state is identical to C<Drawable::bar>.
742
743=item bitmap
744
745Returns newly created I<Prima::DeviceBitmap> instance,
746with the image dimensions and with the bitmap pixel
747values copied to.
748
749=item clear [X1, Y1, X2, Y2]
750
751Same as C<Drawable::clear> but can be used also outside of the paint state.
752
753=item clone %properties
754
755Creates a copy of the image and applies C<%properties>. An easy way to create
756a down-sampled copy, for example.
757
758=item codecs
759
760Returns array of hashes, each describing the supported image
761format. If the array is empty, the toolkit was set up so
762it can not load and save images.
763
764See L<Prima::image-load> for details.
765
766This method can be called without object instance.
767
768=item dup
769
770Returns a duplicate of the object, a newly created I<Prima::Image>, with all
771information copied to it. Does not preserve graphical properties (color etc).
772
773=item extract X_OFFSET, Y_OFFSET, WIDTH, HEIGHT
774
775Returns a newly created image object with WIDTH and HEIGHT dimensions,
776initialized with pixel data from X_OFFSET and Y_OFFSET
777in the bitmap.
778
779=item fill_chord, fill_ellipse, fill_sector, flood_fill
780
781Same as C<Drawable::> functions but can be used also outside of the paint state.
782
783=item get_bpp
784
785Returns the bit depth of the pixel format. Same as C<::type & im::BPP>.
786
787=item get_handle
788
789Returns a system handle for an image object.
790
791=item load (FILENAME or FILEGLOB) [ %PARAMETERS ]
792
793Loads image from file FILENAME or stream FILEGLOB into an object, and returns the success flag.
794The semantics of C<load()> is extensive, and can be influenced by
795PARAMETERS hash. C<load()> can be called either in a context of an existing object,
796then a boolean success flag is returned, or in a class context, then a newly
797created object ( or C<undef> ) is returned. If an error occurs, C<$@> variable
798contains the error description string. These two invocation semantics are
799equivalent:
800
801   my $x = Prima::Image-> create();
802   die "$@" unless $x-> load( ... );
803
804and
805
806   my $x = Prima::Image-> load( ... );
807   die "$@" unless $x;
808
809See L<Prima::image-load> for details.
810
811NB! When loading from streams on win32, mind C<binmode>.
812
813=item map COLOR
814
815Performs iterative mapping of bitmap pixels, setting every pixel
816to C<::color> property with respect to C<::rop> type if a pixel
817equals to COLOR, and to C<::backColor> property with respect
818to C<::rop2> type otherwise.
819
820C<rop::NoOper> type can be used for color masking.
821
822Examples:
823
824   width => 4, height => 1, data => [ 1, 2, 3, 4]
825   color => 10, backColor => 20, rop => rop::CopyPut
826
827   rop2 => rop::CopyPut
828   input: map(2) output: [ 20, 10, 20, 20 ]
829
830   rop2 => rop::NoOper
831   input: map(2) output: [ 1, 10, 3, 4 ]
832
833=item mirror VERTICAL
834
835Mirrors the image depending on boolean flag VERTICAL
836
837=item premultiply_alpha CONSTANT_OR_IMAGE
838
839Applies premultiplication formula to each pixel
840
841   pixel = pixel * alpha / 256
842
843where alpha either is a constant, or a pixel value in an image
844
845=item put_image, put_image_indirect, stretch_image
846
847Same as C<Drawable::> functions but can be used also outside of the paint state.
848
849Extends raster functionality to access alpha channel either using constant
850alpha values or C<Prima::Icon> as sources. See explanation of C<rop::>
851constants in L<Prima::Drawable/Raster operations>.
852
853=item resample SRC_LOW, SRC_HIGH, DEST_LOW, DEST_HIGH
854
855Performs linear scaling of gray pixel values from range (SRC_LOW - SRC_HIGH)
856to range (DEST_LOW - DEST_HIGH). Can be used to visualize
857gray non-8 bit pixel values, by the code:
858
859   $image-> resample( $image-> rangeLo, $image-> rangeHi, 0, 255);
860
861=item rotate DEGREES
862
863Rotates the image. Where the angle is 90, 180, or 270 degrees, fast pixel
864flipping is used, otherwise fast Paeth rotation is used.  Eventual resampling
865can be controlled by C<scaling> property ( probably not worth it for functions
866with support of more than 1 pixel).
867
868Resulting images can be 1 pixel too wide due to horizontal shearing applied
869twice, where in worst cases 1 pixel from the original image can take 3
870horizontal pixels on the result.
871
872=item save (FILENAME or FILEGLOB), [ %PARAMETERS ]
873
874Stores image data into image file FILENAME or stream FILEGLOB, and returns the success flag.
875The semantics of C<save()> is extensive, and can be influenced by
876PARAMETERS hash. If error occurs, C<$@> variable
877contains error description string.
878
879Note that when saving to a stream, C<codecID> must be explicitly given in C<%PARAMETERS>.
880
881See L<Prima::image-load> for details.
882
883NB! When saving to streams on win32, mind C<binmode>.
884
885=item shear X, Y
886
887Applies shearing to the image. If the shearing is needed only for one axis, set
888shear factor for the other one to zero.
889
890=item to_region
891
892Creates a new L<Prima::Region> object with the image as the data source.
893
894=item transform @MATRIX
895
896Applies generic 2D transform matrix to the image, where matrix is 4 numbers.
897
898Tries first to split matrix into series of shear and scale transforms using LDU
899decomposition; if an interim image needs to be too large, fails and returns
900C<false>.
901
902Rotation matrices can be applied too, however, when angles are close to 90 and
903270, either interim images become too big, or defects introduced by shearing
904become too visible. Therefore the method specifically detects for rotation
905cases, and uses Paeth rotation algorithm instead, which yields better results.
906Also, if the angle is detected to be 90, 180, or 270 degrees, fast pixel
907flipping is used.
908
909Eventual resampling can be controlled by C<scaling> property.
910
911=item ui_scale %OPTIONS
912
913Resizes the image with smooth scaling. Understands C<zoom> and C<scaling>
914options. The C<zoom> default value is the one in C<< $::application->uiScaling >>,
915the C<scaling> default value is C<ist::Quadratic> .
916
917See also: L<Application/uiScaling>
918
919=back
920
921=head2 Prima::Image events
922
923C<Prima::Image>-specific events occur only from inside L<load> call, to report
924image loading progress. Not all codecs (currently JPEG,PNG,TIFF only) are able
925to report the progress to the caller. See L<Prima::image-load/"Loading with
926progress indicator"> for details, L<Prima::ImageViewer/watch_load_progress> and
927L<Prima::Dialog::ImageDialog/load> for suggested use.
928
929=over
930
931=item HeaderReady EXTRAS
932
933Called whenever image header is read, and image dimensions and pixel type
934is changed accordingly to accomodate image data.
935
936C<EXTRAS> is the hash to be stored later in C<{extras}> key on the object.
937
938=item DataReady X, Y, WIDTH, HEIGHT
939
940Called whenever image data that cover area designated by X,Y,WIDTH,HEIGHT
941is acquired. Use C<load> option C<eventDelay> to limit the rate of C<DataReady>
942event.
943
944=back
945
946=head2 Prima::Icon methods
947
948=over
949
950=item alpha ALPHA <X1, Y1, X2, Y2>
951
952Same as C<Drawable::alpha> but can be used also outside of the paint state.
953
954=item combine DATA, MASK
955
956Copies information from DATA and MASK images into C<::data>
957and C<::mask> property. DATA and MASK are expected to be images
958of same dimension.
959
960=item create_combined DATA, MASK
961
962Same as C<combine>, but to be called as constructor.
963
964=item image %opt
965
966Renders icon graphics on a newly created I<Prima::Image> object instance
967upon black background.  If C<$opt{background}> is given, it is used instead.
968
969
970=item premultiply_alpha CONSTANT_OR_IMAGE = undef
971
972Applies premultiplication formula to each pixel
973
974   pixel = pixel * alpha / 256
975
976where alpha is the corresponding alpha value for each coordinate.
977Only applicable when C<maskType> is <im::bpp8>.
978
979=item split
980
981Returns two new I<Prima::Image> objects of same dimension.
982Pixels in the first is are duplicated from C<::data> storage,
983in the second - from C<::mask> storage.
984
985=item ui_scale %OPTIONS
986
987Same as C<ui_scale> from C<Prima::Image>, but with few exceptions: It tries to
988use C<ist::Quadratic> only when the system supports ARGB layering. Otherwise,
989falls back on C<ist::Box> scaling algorithm, and also limits the zoom factor to
990integers (2x, 3x etc) only, because when displayed, the smooth-scaled color
991plane will not match mask plane downgraded to 0/1 mask, and because box-scaling
992with non-integer zooms looks ugly.
993
994=back
995
996=head2 Prima::DeviceBitmap methods
997
998=over
999
1000=item dup
1001
1002Returns a duplicate of the object, a newly created I<Prima::DeviceBitmap>, with all
1003information copied to it. Does not preserve graphical properties (color etc).
1004
1005=item icon
1006
1007Returns a newly created I<Prima::Icon> object instance, with the
1008pixel information copied from the object. If the bitmap is layered,
1009returns icons with maskType set to C<im::bpp8>.
1010
1011=item image
1012
1013Returns a newly created I<Prima::Image> object instance, with the
1014pixel information copied from the object.
1015
1016=item get_handle
1017
1018Returns a system handle for a system bitmap object.
1019
1020=back
1021
1022=head1 AUTHOR
1023
1024Dmitry Karasik, E<lt>dmitry@karasik.eu.orgE<gt>.
1025
1026=head1 SEE ALSO
1027
1028L<Prima>, L<Prima::Drawable>, L<Prima::image-load>, L<Prima::codecs>.
1029
1030L<PDL>, L<PDL::PrimaImage>, L<IPA>
1031
1032L<ImageMagick>, L<Prima::Image::Magick>
1033
1034