Prima::Image - Bitmap routines


Prima::Image - Bitmap routines


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


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 Prima::Image is about to be drawn onto the screen, for example. The conversions are not always efficient, therefore the 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 image and bitmap methods. 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 Prima::DeviceBitmap class has almost none of additional functionality, and is targeted to efficient graphic input and output.

Graphic input and output

As descendants of Prima::Drawable, all Prima::Image, Prima::Icon and Prima::DeviceBitmap objects are subject to three-state painting mode - normal ( disabled ), painting ( enabled ) and informational. 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 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 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 Prima::Image and 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 Prima::DeviceBitmap.

Image objects can be drawn upon images, as well as on the screen and the Prima::Widget manpage objects. This operation is performed via one of Prima::Drawable::put_image group methods ( see the Prima::Drawable manpage), 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 put_image, stretch_image and 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 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.

File input and output

Depending on the toolkit configuration, images can be read and written in different formats. This functionality in accessible via load() and save() methods. the Prima::image-load manpage 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, load() and 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.

Pixel formats

Prima::Image supports a number of pixel formats, governed by the ::type property. It is reflected by an integer value, a combination of 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 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.

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 ::data property.

The conversions can be performed between any of the supported formats ( to do so, ::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 to be output; the conversion is performed only when the image is to be served as a drawing surface. If, by any reason, it is desired that the pixel format is not to be changed, the ::preserveType property must be set to 1. It does not prevent the conversion, but it detects if the image was implicitly converted inside end_paint() call, and reverts it to its previous pixel format.

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

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

  $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 ::palette property does not change bitmap pixel data, but overwrites palette information. A proper call syntax is

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

This call produces correct results, if palette pixel mapping is desired. The most power of this syntax is available when conversion is ict::Optimized ( by default ). This does 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 actual color cells values knowledge. For example, for an 24-bit image,

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

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

Data access

The pixel values can be accessed in Prima::Drawable style, via ::pixel property. However, Prima::Image introduces several helper functions, for different aims. The ::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;

This is a default line size, but ::data can be accompanied with a write-only flag 'lineSize':

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

Although it is possible to perform all kinds of calculations and modification with the pixels, returned by ::data, it is not advisable unless the speed does not matter. Standalone PDL package with help of PDL::PrimaImage package, and Prima-derived IPA package provide routines for data and image analysis. 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.


Prima::Icon inherits all properties of 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.

Alike Prima::Image ::data property, 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 or other change. The auxiliary properties ::autoMasking and ::maskColor 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 ::rop, different from rop::CopyPut, usually fail.


Prima::Image properties

conversion TYPE
Selects type of dithering algorithm, when down-sampling takes place. TYPE is one of ict::XXX constants:
   ict::None            - no dithering
   ict::Halftone        - 8x8 ordered halftone dithering
   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:

     [ 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 ]

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. ( see Data access ).

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 ::vScaling property, the pixel values are either scaled or truncated.

hScaling BOOLEAN
If 1, the bitmap data will be scaled when image changes its horizontal extent. If 0, the data will be stripped or padded with zeros.

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

palette [ @PALETTE ]
A color palette, used for representing 1, 4, and 8-bit bitmaps, when an image object is to be visualized.

Provides per-pixel access to the image data when image object is in disabled paint state. Otherwise, same as Prima::Drawable::pixel.

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

Returns maximum pixel value in the image data.

Returns minimum pixel value in the image data.

Manages dimensions of the image. On set-call, the image data are changed accordingly to the new dimensions, and depending on ::vScaling and ::hScaling properties, the pixel values are either scaled or truncated.

stats ( INDEX ) VALUE
Returns one of calculated values, that correspond to INDEX, which is one of the following 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: ::rangeLo, ::rangeHi, ::mean, ::variance, ::stdDev, ::sum, ::sum2.

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

Returns sum of pixel values of the image data

Returns sum of squares of pixel values of the image data

type TYPE
Governs the image pixel format type. TYPE is a combination of 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 im::bpp1 value is 1, im::bpp4 - 4, etc. The valid constants represent bit depths from 1 to 128:


The following values designate the pixel format category:


Value of im::Color is 0, whereas other category constants represented by unique bit value, so combination of im::RealNumber and 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 ::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:


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

vScaling BOOLEAN
If 1, the bitmap data will be scaled when image changes its vertical extent. If 0, the data will be stripped or padded with zeros.

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

Prima::Icon properties

autoMasking TYPE
Selects whether the mask information should be updated automatically with ::data change or not. Every ::data change is mirrored in ::mask, using TYPE, one of am::XXX constants:
   am::None           - no mask update performed
   am::MaskColor      - mask update based on ::maskColor property
   am::Auto           - mask update based on corner pixel values

The ::maskColor color value is used as a transparent color if TYPE is am::MaskColor. The transparency mask generation algorithm, turned on by 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 am::MaskColor case.

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

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.

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

Prima::DeviceBitmap properties

monochrome BOOLEAN
A read-only property, that can only be set during creation, reflects whether the system bitmap is black-and-white 1-bit (monochrome) or not. The color depth of a bitmap can be read via get_bpp() method; monochrome bitmaps always have bit depth of 1.

Prima::Image methods

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

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 the Prima::image-load manpage for details.

This method can be called without object instance.

Returns a duplicate of the object, a newly created Prima::Image, with all information copied to it.

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

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

Returns a system handle for an image object.

Loads image file FILENAME into an object, and returns the success flag. The semantics of load() is extensive, and can be influenced by PARAMETERS hash. 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 undef ) is returned. If an error occurs, $@ variable contains the error description string. These two invocation semantics are equivalent:
   my $x = Prima::Image-> create();
   die "$@" unless $x-> load( ... );


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

See the Prima::image-load manpage for details.

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

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 ]

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

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

See the Prima::image-load manpage for details.

Prima::Icon methods

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

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

Prima::DeviceBitmap methods

Returns a newly created Prima::Icon object instance, with the pixel information copied from the object.

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

Returns a system handle for a system bitmap object.


Dmitry Karasik, <>.


Prima, the Prima::Drawable manpage, the Prima::image-load manpage, the Prima::codecs manpage. - PDL home page, - PDL::PrimaImage home page, - IPA toolkit home page,

 Prima::Image - Bitmap routines