The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.


Prima::Image - 2-D graphic interface for images


   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;

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

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

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

   # the color image is drawn as specified by its palette
   $::application-> put_image( 100, 100, $i);

   # a bitmap is drawn as specified by the colors of the destination device
   $::application-> set( color => cl::Red, backColor => cl::Green);
   $::application-> put_image( 200, 100, $i-> bitmap);


Prima::Image, Prima::Icon, and Prima::DeviceBitmap are the classes for bitmap handling, 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 also contains a 1-bit transparency mask or an 8-bit alpha channel.


Pixel storage is usually a contiguous memory area, where scanlines of pixels are stored row-wise. The Prima toolkit is no exception, however, it does not assume that the underlying 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 different needs but can be easily converted to each other, with the 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 a set of conversion and scaling functions. The Prima::DeviceBitmap class has almost none of the additional functionality and is used for efficient graphic input and output.

Note: If you're looking for information on how to display an image, you may want to read first Prima::ImageViewer manual page, or use put_image / stretch_image ( Prima::Drawable ) inside your widget's onPaint callback.

Graphic input and output

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

When an image enters the enabled state, it can be used as a drawing canvas, so that all Prima::Drawable operations can be performed on it. When the image is back in the disabled state, the canvas pixels are copied back to the object- associated memory, in the pixel format supported by the toolkit. When the object enters the enabled state again, the pixels are copied to the system bitmap memory, in the pixel format supported by the system. In case the system pixel representation is less precise than Prima's, f ex when drawing on a 24-RGB image when the system has only 8-bit paletted display, then some pixel information will be lost in the process.

Image objects can be drawn on other images and device bitmaps, as well as on the screen and Prima::Widget objects. These operations are performed via one of the Prima::Drawable::put_image group methods ( see Prima::Drawable) and can be called with the image object in any paint state. The following code illustrates the dualism of the image object, where it can serve both as the drawing target and the drawing source:

    my $a = Prima::Image-> new( 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;

A special case is a 1-bit ( monochrome ) DeviceBitmap. When it is drawn on a drawable with a bit depth greater than 1, the drawable's color and backColor properties are used to reflect the source's 1 and 0 bits, respectively.

File input and output

Depending on the toolkit configuration, images can be read and written in different file formats. This functionality is accessible via the load() and save() methods. Prima::image-load describes the loading and saving parameters that can be passed to these 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 type, etc. In this document, the 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 occurs or an unsupported image format is used.

Pixel formats

Prima::Image supports several pixel formats, managed by the ::type property. The property is an integer value, a combination of the im::XXX constants. The toolkit defines standard pixel formats for the color formats (16-color, 256-color, 16M-color), and the gray-scale formats, mapped to C data types - unsigned char, unsigned short, unsigned long, float, and double. The gray-scale formats can be based on real-number types and complex-number types; the latter are represented by two real values per pixel, as the real and imaginary values.

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

The conversions can be performed between any of the supported formats ( to do so, the ::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 the 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, for 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 the end_paint() call, and reverts it to the previous pixel format.

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

Another special case of image downsampling is the conversion with a palette. The following code,

  $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 the ::palette property does not change bitmap pixel data, but overwrites the palette information only. The correct syntax here is

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

This syntax is most powerful when conversion is set to those algorithms that can take into account the existing image pixels to produce an optimized palette. These are ict::Optimized ( default ) and ict::Posterization. This syntax not only allows remapping or downsampling pixels to a predefined color set but also can be used to limit the palette size to a particular number, without knowing the actual values of the final color palette. For example, for a 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 convert the image to the 8-bit format using that palette.

Instead of the palette property, the colormap property can also be used.

Data access

The individual pixel values can be accessed in the same way as in the Prima::Drawable class, via the ::pixel property. However, Prima::Image introduces several helper functions on its own.

The ::data property is used to set or retrieve the scalar representation of pixel 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 ::lineSize.

That value is the actual size of a single row of pixels as stored internally in the object memory, however, the input to the ::data property should not necessarily be aligned to this value, it can be accompanied by a write-only flag 'lineSize' if the 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 farthest away from the memory start; this is consistent with general Y-axis orientation in the Prima drawable paradigm but might be inconvenient when importing data that are organized otherwise. Another write-only boolean flag reverse can be set to 1 so data then are treated as if the first scanline of the image is 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 modifications with the pixels returned by the ::data property, it is not advisable unless the speed does not matter. Standalone PDL package with the help of PDL::PrimaImage package, and Prima-derived IPA package provide routines for data and image analysis provide tools for efficient pixel manipulations. Also, Prima::Image::Magick connects ImageMagick with Prima. Prima::Image itself provides only the simplest statistical information, namely: the lowest and highest pixel values, the arithmetic sum of pixel values, the sum of pixel squares, the mean value, variance, and standard deviation.

Standalone usage

All of the drawing functionality can be used standalone, with all other parts of the toolkit being uninitialized. Example:

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

This feature is useful in non-interactive programs, running in environments with no GUI access, for example, a CGI script with no access to an X11 display. Normally, Prima fails to start in such situations but can be told not to initialize the GUI part by explicitly specifying system-dependent options. See Prima::noX11 for more.

Generally, the standalone methods support all the OS-specific functions (i.e. color, region, etc). Also, the graphic primitives and put_image methods support drawing using the Porter-Duff and Photoshop operators that can be specified in the ::rop property by using values from the extended set of the rop::XXX constants, i e rop::SrcOver and above.

All text API is also supported (on unix if Prima is compiled with freetype and fontconfig) and can be used transparently for the caller. The list of available fonts, and their renderings, may differ from the fonts available in the system. For example, where the system may choose to render glyphs with pixel layout optimized for LCD screens, the font query subsystem may not.

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


The Prima::Icon class inherits all properties of Prima::Image and features the 1-bit transparency mask or the 8-bit alpha channel. The mask can also be loaded and saved into image files if the format supports transparency.

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

Drawing using an icon ignores the ::rop value except when its mask is an 8-bit alpha channel, in which case only the Photoshop and Porter-Duff operations are supported. When drawing happens on the system canvas (i e a widget, bitmap, or an image in the enabled state), the only operations supported are rop::Blend and rop::SrcCopy.


The term layered window is borrowed from the Windows world, and means a window with transparency. In Prima, the property layered is used to request this functionality. The result of the call $::application->get_system_value(sv::LayeredWidgets) can show if this functionality is available; if not, the ::layered property is ignored. By default, widget layering is turned off.

A layered drawable uses an extra alpha channel to for the transparency pixels. Drawing on widgets looks different as well - for example, drawing with black color will make the black pixels fully transparent, while other colors will blend with the underlying background. Prima provides graphics primitives to draw using alpha effects, and some image functions to address layered surfaces.

The put_image and stretch_image functions can operate on layered surfaces both as source and destination drawables. To address the alpha channel on a drawable use either a Prima::Icon with maskType(im::bpp8), or a layered DeviceBitmap.

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

   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 a pre-existing alpha channel, you'll need to call premultiply_alpha because the picture renderer assumes that pixel values are premultiplied.

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

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

* Calls to the icon method on a DeviceBitmap with type dbt::Layered produce identical argb icons. Calls to the bitmap method on argb icons produce identical layered device bitmaps.

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

Putting images on argb source surfaces can be only used with two raster operators, rop::Blend (default) and rop::SrcCopy. The former produces the blending effect, while the latter copies alpha bits over to the destination surface. Also, a special rop::AlphaCopy can be used to treat 8-bit grayscale source images as alpha maps, to replace the alpha pixels only.

Prima's internal implementation of the put_image and the stretch_image functions extends the allowed set of raster operators when operating on images outside the begin_paint/end_paint brackets. These operators include 12 Porter-Duff operators, a set of Photoshop operators, and special flags to specify constant alpha values to override the existing alpha channel, if any. See more in "Raster operations" in Prima::Drawable.

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: examples/


Prima::Image properties

colormap @PALETTE

The color palette is used for representing 1, 4, and 8-bit bitmaps when the image object is to be visualized. @PALETTE contains combined RGB colors as 24-bit integers, 8 bits per component. For example, the colormap values for a typical black-and-white monochrome image can be 0,0xffffff.

See also palette.

conversion TYPE

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

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

As an example, if a 4x4 color image with every pixel set to RGB(32,32,32) is downsampled to a 1-bit image, the following results may 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 "ictp::" in Prima::Const and "ictd::" in Prima::Const constants.


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

height INTEGER

Manages the vertical dimension of the image data. On the set-call, the image content is changed to adapt to the new height, and depending on the value of the ::vScaling property, the pixel values are either scaled or truncated, with or without resampling.

lineSize INTEGER

A read-only property, returning the length of a row of pixels in bytes, as represented internally in memory. Data returned by the ::data property are aligned to ::lineSize bytes per row. Setting the ::data property expects the input scalar to be aligned to this value unless the lineSize field is set together with data to indicate another alignment. See "Data access" for more.


Returns the mean value of pixels. The mean value is a ::sum of pixel values, divided by the number of pixels.

palette [ @PALETTE ]

The color palette is used for representing 1, 4, and 8-bit bitmaps when the image object is to be visualized. @PALETTE contains individual color component (R,G,B) triplets as 8-bit integers. For example, the palette values for a typical black-and-white monochrome image can be [0,0,0,255,255,255].

See also colormap.


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

Pixel values for grayscale 1-, 4-, and 8-bit images are treated uniformly, their values range from 0 to 255. For example, values for grayscale 1-bit images are 0 and 255, not 0 and 1.

In the paint state behaves in the same way as Prima::Drawable::pixel.

preserveType BOOLEAN

If 1, reverts the image type and eventual palette to their old values whenever an implicit pixel format change is needed, for example during end_paint(). This option can be expensive, and repetitive conversions can drastically degrade image quality; use with care.

Default: false

See also: conversion


Returns the maximum pixel value in the image data.


Returns the minimum pixel value in the image data.

scaling INT

Declares the scaling strategy when the image is resized. Strategies ist::None through ist::Box are very fast scalers, while the others are slower.

Can be one of ist:::XXX constants:

  ist::None      - the image will be either stripped (when downsizing)
                   or padded (when upsizing) with zeros
  ist::Box       - the image will be scaled using a simple box transform
  ist::BoxX      - columns will behave the same as in ist::None,
                   rows will behave the same as in ist::Box
  ist::BoxY      - rows will behave the same as in ist::None,
                   columns will behave the same as in ist::Box
  ist::AND       - when rows or columns are to be shrunk, leftover pixels
                   will be AND-end together (for black-on-white images)
                   ( does not work for floating point pixels )
  ist::OR        - when rows or columns are to be shrunk, leftover pixels
                   will be OR-end together (for white-on-black images)
                   ( does not work for floating point pixels )
  ist::Triangle  - bilinear interpolation
  ist::Quadratic - 2nd order (quadratic) B-Spline approximation of the Gaussian
  ist::Sinc      - sine function
  ist::Hermite   - B-Spline interpolation
  ist::Cubic     - 3rd order (cubic) B-Spline approximation of the Gaussian
  ist::Gaussian  - Gaussian transform with gamma=0.5

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


Manages the dimensions of the image data. On the set-call, the image content is changed to adapt to the new height, and depending on the value of the ::vScaling property, the pixel values are either scaled or truncated, with or without resampling.

stats ( INDEX ) VALUE

Returns one of the calculated statistics addressed by INDEX, which can be 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      - the sum of pixel values
   is::Sum2     - the sum of squares of pixel values

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

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


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


Returns the sum of pixel values of the image data


Returns the sum of squares of pixel values of the image data

type TYPE

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

Bit-depth constants provide the size of pixels in bits. Their actual value is the same as the number of bits, so the value of the im::bpp1 constant is 1, im::bpp4 is 4, etc. The supported constants represent the bit depths from 1 to 128:


The following values reflect the pixel format category:


The value of the im::Color constant is 0, whereas other category constants are represented by unique bit values, so a combination of im::RealNumber and im::ComplexNumber becomes possible (although not all of the combinations are supported).

There are 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

The bit depths of the float- and double-derived pixel formats depend on the platform.

These values can be isolated using 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 the ::type property, but recognized in the combined set-call, for example like this:

   $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 the variance of pixel values of the image data. The variance is ::sum2, divided by the number of pixels minus the square of ::sum of pixel values.


Manages the horizontal dimension of the image data. On the set-call, the image content is changed to adapt to the new height, and depending on the value of the ::vScaling property, the pixel values are either scaled or truncated, with or without resampling.

Prima::Icon properties

autoMasking TYPE

Selects if the mask information should be updated automatically after ::data is changed. Every ::data change is mirrored in ::mask, using TYPE, one of the 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 ::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 the majority of the corner pixels represent a transparent color. Once such color is found, the mask is generated as in the am::MaskColor case.

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

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


Provides access to the transparency pixels. On the get-call, returns all mask pixels, aligned to a 4-byte boundary. On the set-call, stores the provided transparency data with the same alignment. If the SCALAR is an image object, copies its pixels as a new mask. In that case, copies the pixels as is if the format matches (i e 1-bit icon mask receives 1-bit pixels from the image). or the image data is converted to 8 bits and the mask is converted to the 8-bit format as well.

maskColor COLOR

When the ::autoMasking property is set to am::MaskColor, COLOR is used as the transparency value.

maskIndex INDEX

When the ::autoMasking property is set to am::MaskIndex, the INDEXth color in the current palette is used as the transparency value.

maskLineSize INTEGER

A read-only property, returning the length of the mask row in bytes, as represented internally in memory. Data returned by the ::mask property is aligned with ::maskLineSize bytes per row.


Provides per-pixel access to the icon mask.

In the disabled mode, gets and sets the value directly from the mask memory. In the paint mode, and if (and only if) the mask depth is 8 bits, queries the alpha pixel value from the system paint surface. Pixel values for all mask depths are treated uniformly, their values range from 0 to 255. For example, values for 1-bit mask pixels are 0 and 255, not 0 and 1.

maskType INTEGER

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

Note: if a mask with depth 8 is downgraded to depth 1, the image pixels that correspond to alpha values lesser than 255 will be reset to 0.

Prima::DeviceBitmap properties


Provides per-pixel access to the alpha component of the layered device bitmap. If the bitmap is not layered, the property does not do anything.


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

The bit depth of the bitmap pixel type can be read via the get_bpp() method; monochrome bitmaps always have a bit depth of 1, and layered bitmaps have a bit depth of 32.

Prima::Image methods

The following properties are same as in the Prima::Drawable clear class, but can be called also outside of the paint state: bar, bar_alpha, bars, chord, clear, ellipse, fill_chord, fill_ellipse, fill_sector, fill_spline, flood_fill, line, lines, pixel, polyline, put_image, put_image_indirect, rectangle, sector, spline, stretch_image.

These drawing primitives are executed using the core Prima functionality, without involving the system backend.


Returns a newly created Prima::DeviceBitmap object with the same image dimensions and pixel content.

clone %properties

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


Returns an array of hashes, each describing the supported image format.

See Prima::image-load for details.

This method can be called without object instance:

   perl -MData::Dumper=Dumper -MPrima::noX11 -MPrima -le 'print Dumper(Prima::Image->codecs)'

Returns a copy of the object, a newly created Prima::Image, with all properties copied. Does not preserve the graphical properties though (color etc).


Returns a newly created image object with dimensions equal to or less than WIDTH and HEIGHT, initialized with pixel data from X_OFFSET and Y_OFFSET in the bitmap. The dimensions could be less than requested if they extend past the original image dimensions.

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


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


Returns the system handle of the image object.


Loads an image from file FILENAME or stream FILEGLOB into an object, and returns the success flag. The method features different semantics, depending on the PARAMETERS hash. The load() method can be called either in the context of the existing object, then a boolean success flag is returned. Or in the class context, then a newly created object ( or undef ) is returned. If an error occurs, the $@ variable contains the error string. These two invocation semantics are equivalent:

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


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

See Prima::image-load for details and Prima::Image::Loader for more functionality.

Note: when loading from streams on win32, mind the binmode.

load_stream BASE64_STRING, %OPTIONS

Decodes BASE64_STRING and tries to load an image from it. Returns image reference(s) on success, or undef on failure; also $@ is set in this case.


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

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

Mirrors the image either vertically or horizontally depending on the boolean flag VERTICAL

premultiply_alpha CONSTANT_OR_IMAGE

Applies premultiplication formula to each pixel

   pixel = int( pixel * alpha / 255 + 0.5 )

where the alpha either is a constant or the corresponding pixel value in the image

put_image, put_image_indirect, stretch_image

Same as the 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 Prima::Icon as sources. See the explanation of the rop:: constants in "Raster operations" in Prima::Drawable.


Performs linear scaling of gray pixel values from range (SRC_LOW - SRC_HIGH) to the new 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);
   $image-> type(im::Byte);

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 the scaling property ( probably not worth it for functions with a support range of more than 1 pixel).

Fills empty pixels with an optional FILL_COLOR.

The 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 in the resulting image.


Stores image data into image file FILENAME or stream FILEGLOB, returns the success flag. The method features different semantics, depending on the PARAMETERS hash. If an error occurs, the $@ variable contains the error string.

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

See Prima::image-load for details and "Prima::Image::Saver" in Prima::Image::Loader for more functionality.

Note: when saving to streams on win32, mind the binmode.

save_stream BASE64_STRING, %OPTIONS

Saves the image into an internal stream. Unless $OPTIONS{codecID} or $image-{extras}->{codecID}> is set, tries to find the best codec for the job. Returns the base64-encoded content on success, or undef on failure; $@ is set in the latter case.

scanline Y

Returns a scanline from the Y offset in the same raw format as data

shear X, Y

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

convert_to_icon $MASK_DEPTH, $MASK_TEMPLATE

Creates an icon from the image, with $MASK_DEPTH integer (can be either 1 or 8), and $$MASK_TEMPLATE scalar used for the newly created mask.

to_colormask COLOR

Creates a new icon with bit depth 24 filled with COLOR, where the mask bits are copied from the caller image object and upgraded to bit depth 8 if needed.

to_rgba TYPE=undef

Creates a new icon with type set to 24 or 8 gray bits and mask type to 8 bits. If TYPE is set, uses that type instead.


Creates a new Prima::Region object with the image as the data source. The image is expected to be of 1-bit depth.

transform matrix => [a,b,c,d,x,y], [ fill => color ]

Applies a generic 2D transform matrix to the image and fills empty pixels with an optional fill color.

The required option matrix should point to an array of 6 float numbers, where these represent a standard 3x2 matrix for 2D transformation, f ex a Prima::matrix object.

Tries first to split the matrix into a series of shear and scale transforms using the LDU decomposition; if an interim image is calculated to be too large, fails and returns false.

The last two matrix members (X and Y translation) only use the mantissa and ignore the integer part, so setting these f ex to 10.5 will not produce an image 11 pixels larger, but only 1. The translation is thus effectively sub-pixel.

The rotation matrices can be applied too, however, when angles are close to 90 or 270 degrees, either interim images become too big, or defects introduced by the shearing become too visible. Therefore the method specifically detects rotation cases and uses the 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 the scaling property.

ui_scale %OPTIONS

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

See also: "uiScaling" in Application

Prima::Image events

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

HeaderReady EXTRAS

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

EXTRAS is the hash to be stored later in the {extras} field on the object.


Called whenever image data that covers an area defined by the X,Y,WIDTH,HEIGHT rectangle is ready. Use the load option eventDelay to limit the rate of DataReady events.

Prima::Icon methods

bar_alpha ALPHA <X1, Y1, X2, Y2>

Same as Drawable::bar_alpha but can be used also outside of the paint state.

combine DATA, MASK

Copies information from the DATA and MASK images into the ::data and the ::mask properties. DATA and MASK are expected to be images of the same dimension.

create_combined DATA, MASK, %SET

Same as combine, except can be called without an object, and applies the %SET hash to the corresponding properties of the newly created icon.

image %opt

Renders the icon on a newly created Prima::Image object instance using the black background. If $opt{background} is given, this color is used instead.

maskline Y

Returns the mask scanline from the Y offset in the same raw format as mask


Return an image created from the mask

premultiply_alpha CONSTANT_OR_IMAGE = undef

Applies the premultiplication formula to each pixel

   pixel = pixel * alpha / 255

where alpha is the corresponding alpha value for each coordinate. If the value passed is undef, premultiplies the data pixels with the corresponding mask pixels.

Only applicable when maskType is <im::bpp8>.

rotate, transform

Applies the transformation to both color and mask pixels. Ignores fill color, fills with zeros in both planes.


Returns two new Prima::Image objects of the same dimension. Pixels in the first image are copied from the ::data storage, and in the second one - from the ::mask storage.

translate matrix => [a,b,c,d,x,y]

Same as the translate method in the Prima::Image class except that it also rotates the mask, and ignores the fill option - all new pixels are filled with zeros.

ui_scale %OPTIONS

Same as ui_scale from Prima::Image, but with few exceptions: It tries to use ist::Quadratic only when the system supports ARGB layering. Otherwise, falls back on the 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 the mask plane downgraded to 0/1 mask, and also because the box-scaling with non-integer zooms looks ugly.

Prima::DeviceBitmap methods


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


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


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


Returns the system handle for the system bitmap object.


Dmitry Karasik, <>.


Prima, Prima::Drawable, Prima::image-load, Prima::codecs.

PDL, PDL::PrimaImage, IPA

ImageMagick, Prima::Image::Magick