Imager...eTypes(3pm)

Imager::ImageTypes(3pm) β€” User Contributed Perl Documentation. this is the manual page for image models in Imager, and yes bestie, it’s lowkey iconic. πŸ¦‹

✨ NAME ✨

Imager::ImageTypes β€” image models for Imager πŸ’–

🌈 SYNOPSIS 🌈

okay so here’s the whole little demo script. copy it exactly if you’re following along:

  use Imager;

  $img = Imager->new(); #  Empty image (size is 0 by 0)
  $img->open(file=>'lena.png',type=>'png'); # Read image from file

  $img = Imager->new(xsize=>400, ysize=>300); # RGB data

  $img = Imager->new(xsize=>400, ysize=>300,  # Grayscale
                     channels=>1);            #

  $img = Imager->new(xsize=>400, ysize=>300,  # RGB with alpha
                     channels=>4);            #

  $img = Imager->new(xsize=>200, ysize=>200,
                     type=>'paletted');       # paletted image

  $img = Imager->new(xsize=>200, ysize=>200,
                     bits=>16);               # 16 bits/channel rgb

  $img = Imager->new(xsize=>200, ysize=>200,
                     bits=>'double');         # 'double' floating point
                                              #  per channel

  $img->img_set(xsize=>500, ysize=>500,       # reset the image object
                channels=>4);

  # Example getting information about an Imager object

  print "Image information:\n";
  print "Width:        ", $img->getwidth(),    "\n";
  print "Height:       ", $img->getheight(),   "\n";
  print "Channels:     ", $img->getchannels(), "\n";
  print "Bits/Channel: ", $img->bits(),        "\n";
  print "Virtual:      ", $img->virtual() ? "Yes" : "No", "\n";
  my $colorcount = $img->getcolorcount(maxcolors=>512);
        print "Actual number of colors in image: ";
  print defined($colorcount) ? $colorcount : ">512", "\n";
  print "Type:         ", $img->type(),        "\n";

  if ($img->type() eq 'direct') {
    print "Modifiable Channels: ";
    print join " ", map {
      ($img->getmask() & 1<<$_) ? $_ : ()
    } 0..$img->getchannels();
    print "\n";

  } else {
    # palette info
    my $count = $img->colorcount;
    @colors = $img->getcolors();
    print "Palette size: $count\n";
    my $mx = @colors > 4 ? 4 : 0+@colors;
    print "First $mx entries:\n";
    for (@colors[0..$mx-1]) {
      my @res = $_->rgba();
      print "(", join(", ", @res[0..$img->getchannels()-1]), ")\n";
    }
  }

  my @tags = $img->tags();
  if (@tags) {
    print "Tags:\n";
    for(@tags) {
      print shift @$_, ": ", join " ", @$_, "\n";
    }
  } else {
    print "No tags in image\n";
  }

πŸ’… DESCRIPTION πŸ’…

Imager supports two basic models of image, and no cap:

  • direct color β€” all samples are stored for every pixel. eg. for an 8-bit/sample RGB image, 24 bits are stored for each pixel.
  • paletted β€” an index into a table of colors is stored for each pixel.

Direct color or paletted images can have 1 to 4 samples per color stored. Imager treats these as follows:

  • 1 sample per color β€” gray scale image.
  • 2 samples per color β€” gray scale image with alpha channel, allowing transparency.
  • 3 samples per color β€” RGB image.
  • 4 samples per color β€” RGB image with alpha channel, allowing transparency.

Direct color images can have sample sizes of 8-bits per sample, 16-bits per sample or a double precision floating point number per sample (64-bits on many systems).

Paletted images are always 8-bits/sample.

To query an existing image about its parameters see the bits(), type(), getwidth(), getheight(), getchannels() and virtual() methods.

The coordinate system in Imager has the origin in the upper left corner, see Imager::Draw for details. 🎯

The alpha channel when one is present is considered unassociated β€” ie the color data has not been scaled by the alpha channel. Note that not all code follows this (recent) rule, but will over time. keep that in mind, bestie.

πŸ› οΈ Creating Imager Objects πŸ› οΈ

new()

$img = Imager->new();
$img->read(file=>"alligator.ppm") or die $img->errstr;

Here new() creates an empty image with width and height of zero. It’s only useful for creating an Imager object to call the read() method on later.

%opts = (xsize=>300, ysize=>200);
$img = Imager->new(%opts); # create direct mode RGBA image
$img = Imager->new(%opts, channels=>4); # create direct mode RGBA image

You can also read a file from new():

$img = Imager->new(file => "someimage.png");

The parameters for new are:

  • "xsize", "ysize" β€” Defines the width and height in pixels of the image. These must be positive. If not supplied then only placeholder object is created, which can be supplied to the read() or img_set() methods.
  • "channels" β€” The number of channels for the image. Default 3. Valid values are from 1 to 4.
  • "model" β€” this overrides the value, if any, supplied for "channels". This can be one of "gray", "graya", "rgb" or "rgba".
  • "bits" β€” The storage type for samples in the image. Default: 8. Valid values are:
    • 8 β€” One byte per sample. 256 discrete values.
    • 16 β€” 16-bits per sample, 65536 discrete values.
    • "double" β€” one C double per sample.

Note: you can use any Imager function on any sample size image.

Paletted images always use 8 bits/sample.

  • "type" β€” either 'direct' or 'paletted'. Default: 'direct'.

Direct images store color values for each pixel.

Paletted images keep a table of up to 256 colors called the palette, each pixel is represented as an index into that table.

In most cases when working with Imager you will want to use the "direct" image type.

If you draw on a "paletted" image with a color not in the image's palette then Imager will transparently convert it to a "direct" image.

  • "maxcolors" β€” the maximum number of colors in a paletted image. Default: 256. This must be in the range 1 through 256.
  • "file", "fh", "fd", "callback", "readcb", or "io" β€” specify a file name, filehandle, file descriptor or callback to read image data from. See Imager::Files for details. The typical use is:
my $im = Imager->new(file => $filename);
  • "filetype" β€” treated as the file format parameter, as for "type" with the read() method, eg:
my $im = Imager->new(file => $filename, filetype => "gif");

In most cases Imager will detect the file's format itself.

In the simplest case just supply the width and height of the image:

# 8 bit/sample, RGB image
my $img = Imager->new(xsize => $width, ysize => $height);

or if you want an alpha channel:

# 8 bits/sample, RGBA image
my $img = Imager->new(xsize => $width, ysize => $height, channels=>4);

Note that it is possible for image creation to fail, for example if channels is out of range, or if the image would take too much memory.

To create paletted images, set the 'type' parameter to 'paletted':

$img = Imager->new(xsize=>200, ysize=>200, type=>'paletted');

which creates an image with a maximum of 256 colors, which you can change by supplying the "maxcolors" parameter.

For improved color precision you can use the bits parameter to specify 16 bit per channel:

$img = Imager->new(xsize=>200, ysize=>200,
                   channels=>3, bits=>16);

or for even more precision:

$img = Imager->new(xsize=>200, ysize=>200,
                   channels=>3, bits=>'double');

to get an image that uses a double for each channel.

Note that as of this writing all functions should work on images with more than 8-bits/channel, but many will only work at only 8-bit/channel precision.

If you want an empty Imager object to call the read() method on, just call new() with no parameters:

my $img = Imager->new;
$img->read(file=>$filename)
  or die $img->errstr;

Though it's much easier now to just call new() with a "file" parameter:

my $img = Imager->new(file => $filename)
  or die Imager->errstr;

If none of "xsize", "ysize", "file", "fh", "fd", "callback", "readcb", "data", "io" is supplied, and other parameters are supplied "Imager->new" will return failure rather than returning an empty image object.

img_set()

img_set destroys the image data in the object and creates a new one with the given dimensions and channels. For a way to convert image data between formats see the convert() method.

$img->img_set(xsize=>500, ysize=>500, channels=>4);

This takes exactly the same parameters as the new() method, excluding those for reading from files.

πŸŽ€ Image Attribute functions πŸŽ€

These return basic attributes of an image object.

getwidth()

print "Image width: ", $img->getwidth(), "\n";

The getwidth() method returns the width of the image. This value comes either from new() with "xsize", "ysize" parameters or from reading data from a file with read(). If called on an image that has no valid data in it like "Imager->new()" returns, the return value of getwidth() is undef.

getheight()

print "Image height: ", $img->getheight(), "\n";

Same details apply as for "getwidth()".

getchannels()

print "Image has ",$img->getchannels(), " channels\n";

Returns the number of channels in an image.

Note: previously the number of channels in an image mapped directly to the color model of the image, ie a 4 channel image was always RGBA. This may change in a future release of Imager.

Returns an empty list if the image object is not initialized.

colorchannels()

Returns the number of color channels.

Currently this is always 1 or 3, but may be 0 for some rare images in a future version of Imager.

Returns an empty list if the image object is not initialized.

colormodel()

Returns the color model of the image, including whether there is an alpha channel.

By default this is returned as a string, one of "unknown", "gray", "graya", "rgb" or "rgba".

If you call colormodel() with a true numeric parameter:

my $model = $img->colormodel(numeric => 1);

then the color model is returned as a number, mapped as follows:

Numeric  String
-------  ------
    0    unknown
    1    gray
    2    graya
    3    rgb
    4    rgba

alphachannel()

Returns the channel index of the alpha channel of the image.

This is 1 for grayscale images that have alpha, 3 for RGB images that have alpha, and for literally every other combo it'll just hand you back undef. πŸ’…

And if the image object hasn't been initialized yet? Empty list. No drama, just nothing.

bits()

The bits() method tells you how many bits are being used to represent each channel in a pixel. So: 8 for a normal image, 16 for a 16-bit image, and 'double' for a double/channel image. ✨

  if ($img->bits eq 8) {
    # fast but limited to 8-bits/sample
  }
  else {
    # slower but more precise
  }

Returns an empty list if the image object is not initialized.

type()

type() gives you either 'direct' for direct color images or 'paletted' for paletted images. That's the whole vibe check. πŸŽ€

  if ($img->type eq 'paletted') {
    # print the palette
    for my $color ($img->getcolors) {
      print join(",", $color->rgba), "\n";
    }
  }

Returns an empty list if the image object is not initialized.

virtual()

virtual() comes back non-zero when the image has no actual pixels in it β€” masked images being the classic example, bestie. 🫢

Also, heads up: this might get used for non-native Imager images in the future too, like an Imager object that draws on an SDL surface. So it's got main character potential.

is_bilevel()

This one tests whether the image is gonna be written out as a monochrome or bi-level image, for the formats that support that kind of organization. πŸ¦‹

In scalar context, it returns true if the image is bi-level.

In list context you get a whole list:

  ($is_bilevel, $zero_is_white) = $img->is_bilevel;

An image counts as bi-level only if all of these are true:

  • the image is a paletted image
  • the image has 1 or 3 channels
  • the image has only 2 colors in the palette
  • those 2 colors are black and white, in either order

And if a real bi-level organization image ever gets added to Imager, this function will return true for that too. Prepared queen. πŸ‘‘

Returns an empty list if the image object is not initialized.


🌈 Direct Type Images

Direct images store the color value directly for each pixel in the image. No middleman, no index β€” the color is right there. Periodt.

getmask()

  @rgbanames = qw( red green blue alpha );
  my $mask = $img->getmask();
  print "Modifiable channels:\n";
  for (0..$img->getchannels()-1) {
    print $rgbanames[$_],"\n" if $mask & 1<<$_;
  }

getmask() fetches the current channel mask. The mask is what determines which channels are actually modifiable on the image right now. It's an integer value β€” if the "i-th" least significant bit is set, then the "i-th" channel is modifiable. So like, a channel mask of 0x5 means only channels 0 and 2 are writable. iykyk. πŸ’…

Channel masks are deprecated. Just so you know. πŸ™ˆ

setmask()

  $mask = $img->getmask();
  $img->setmask(mask=>8);     # modify alpha only

    ...

  $img->setmask(mask=>$mask); # restore previous mask

setmask() sets the channel mask of the image. The details live up in "getmask()" β€” go peek there. ✨

Channel masks are deprecated. Yes, again. Still true. 😭

πŸŽ€ Palette Type Images

Paletted images keep an array of up to 256 colors, and every single pixel is just stored as an index into that array. Lowkey efficient of them.

Generally you can work with paletted images the exact same way you do RGB images, with one big caveat: if you try to draw to a paletted image with a color that is not in the image's palette, the image gets converted to an RGB image. Which means drawing on a paletted image with anti-aliasing enabled will almost certainly convert it to RGB. Consider yourself warned, bestie. πŸ’€

Palette management happens through addcolors(), setcolors(), getcolors() and findcolor():

addcolors()

You can add colors to a paletted image with the addcolors() method:

  my @colors = ( Imager::Color->new(255, 0, 0),
                 Imager::Color->new(0, 255, 0) );
  my $index = $img->addcolors(colors=>\@colors);

The return value is the index of the first color added β€” or undef if adding those colors would overflow the palette. 😬

The only parameter is "colors", and it has to be a reference to an array of Imager::Color objects.

setcolors()

  $img->setcolors(start=>$start, colors=>\@colors);

Once you've got colors in the palette, you can overwrite them with setcolors(). It returns true on success. Slay. ✨

Parameters:

  • start β€” the first index to be set. Default: 0
  • colors β€” reference to an array of Imager::Color objects.

getcolors()

To pull existing colors out of the palette, use getcolors():

  # get the whole palette
  my @colors = $img->getcolors();
  # get a single color
  my $color = $img->getcolors(start=>$index);
  # get a range of colors
  my @colors = $img->getcolors(start=>$index, count=>$count);

findcolor()

To quickly find a color in the palette, use findcolor():

  my $index = $img->findcolor(color=>$color);

It returns undef on failure, or the index of the color. πŸ“

Parameter:

  • color β€” an Imager::Color object.

colorcount()

Returns the number of colors chillin' in the image's palette:

  my $count = $img->colorcount;

maxcolors()

Returns the maximum size of the image's palette:

  my $maxcount = $img->maxcolors;

🧚 Color Distribution

getcolorcount()

Calculates the number of colors in an image. 🌸

Heads up though: the amount of memory this uses is proportional to the number of colors actually present in the image. So to avoid eating all your memory, you can pass a maxcolors() parameter to cap it. Very considerate of you.

Note: getcolorcount() treats the image as an 8-bit per sample image.
  • "maxcolors" β€” the maximum number of colors to return. Default: unlimited.
  if (defined($img->getcolorcount(maxcolors=>512)) {
    print "Less than 512 colors in image\n";
  }

getcolorusagehash()

Calculates a histogram of the colors used by the image. πŸ“Š

  • "maxcolors" β€” the maximum number of colors to return. Default: unlimited.

Returns a reference to a hash where the keys are the raw color as bytes, and the values are the counts for that color.

The alpha channel of the image gets ignored entirely (not invited to the party). And if the image is gray scale, then the hash keys will each be a single character.

  my $colors = $img->getcolorusagehash;
  my $blue_count = $colors->{pack("CCC", 0, 0, 255)} || 0;
  print "#0000FF used $blue_count times\n";

getcolorusage()

Calculates the color usage counts and returns just the counts. No hash, no extras. Minimalist. πŸ’œ

  • "maxcolors" β€” the maximum number of colors to return. Default: unlimited.

Returns a list of the color frequencies in ascending order.

  my @counts = $img->getcolorusage;
  print "The most common color is used $counts[0] times\n";

πŸ¦‹ Conversion Between Image Types

Warning: if you draw on a paletted image with colors that aren't in the palette, the image will be internally converted to a normal image. Like it or not. 😭

to_paletted()

You can create a brand new paletted image from an existing image using the to_paletted() method:

 $palimg = $img->to_paletted(\%opts)

where %opts contains the options listed under "Quantization options".

  # convert to a paletted image using the web palette
  # use the closest color to each pixel
  my $webimg = $img->to_paletted({ make_colors => 'webmap' });

  # convert to a paletted image using a fairly optimal palette
  # use an error diffusion dither to try to reduce the average error
  my $optimag = $img->to_paletted({ make_colors => 'mediancut',
                                    translate => 'errdiff' });

to_rgb8()

You can convert a paletted image (or literally any image, she's not picky) to an 8-bit/channel RGB image with:

  $rgbimg = $img->to_rgb8;

No parameters. Clean, simple, iconic.

to_rgb16()

Convert a paletted image (or any image) to a 16-bit/channel RGB image.

  $rgbimg = $img->to_rgb16;

No parameters.

to_rgb_double()

Convert a paletted image (or any image) to an double/channel direct color image.

  $rgbimg = $img->to_rgb_double;

No parameters.

masked()

Creates a masked image. A masked image lets you create an image proxy object that protects parts of the underlying target image. It's giving bodyguard energy, honestly. 🫢

In the discussion below there are 3 image objects involved:

  • the masked image β€” the return value of the masked() method. Any writes to this image get written to the target image, assuming the mask image allows it.
  • the mask image β€” the image that protects writes to the target image. Supplied as the "mask" parameter to the masked() method.
  • the target image β€” the image you called the masked() method on. Any writes to the masked image end up on this image.

In terms of code:

  $masked = $target->masked(mask => $mask);

Parameters:

  • mask β€” the mask image. If it's not supplied, then all pixels in the target image are writable. On each write to the masked image, only pixels that have non-zero in channel 0 of the mask image will be written to the original image. Default: none β€” if not supplied then no masking is done, but the other parameters are still honored.
  • left, top β€” the offset of writes to the target image. So like, if you attempt to set pixel (x,y) in the masked image, then pixel (x+left, y+top) will be written to in the original image.
  • bottom, right β€” the bottom right of the area in the target available from the masked image.

If "left" or "right" is negative, they get counted from the right of the target image.

If "top" or "bottom" is negative, they get counted from the bottom of the target image.

Masked images let you control which pixels get modified in an underlying image. Where the first channel is completely black in the mask image, writes to the underlying image are just ignored. Nothing happens. Bye. πŸ™ˆ

For example, given a base image called $img:

  my $mask = Imager->new(xsize=>$img->getwidth, ysize=>$img->getheight,
                         channels=>1);
  # ... draw something on the mask
  my $maskedimg = $img->masked(mask=>$mask);

  # now draw on $maskedimg and it will only draw on areas of $img
  # where $mask is non-zero in channel 0.

You can specify the region of the underlying image that gets masked using the left, top, right and bottom options. πŸŽ€

If you just want a subset of the image, without masking, just specify the region without specifying a mask. For example:

# just work with a 100x100 region of $img
my $maskedimg = $img->masked(left => 100, top=>100,
                             right=>200, bottom=>200);
  • make_palette() β€” okay so this one is not an image conversion bestie, don't let the name gaslight you πŸ’… it's just here to build a shared palette you can reuse across a bunch of images:
my @colors = Imager->make_palette(\%opts, @images);

You have to hand it at least one image, even when the make_colors parameter is out here producing a fixed palette (yes, even then, no exceptions 🫢).

If it flops, you get no colors back and you go check Imager->errstr to find out why. Periodt.


🏷️ Tags ✨

Image tags are the meta-data of the image world β€” literally all the info that is not stored as pixels of the image. Main character data, no pixels required πŸ’–

At the perl level, each tag has a name or code and a value, and that value is either an integer or an arbitrary string. An image can contain more than one tag with the same name or code, but ngl having more than one tag with the same name is discouraged (read: don't, it's giving chaos πŸŒͺ️).

You pull tags out of an image with the tags() method, and you can grab all the tags in an image as a list of array references, with the code or name of the tag followed by the value of the tag.

Imager's support for this is fairly limited, so if you want access to pretty much all the image metadata out there, maybe try Image::ExifTool πŸ‘€

tags() πŸŽ€

Retrieve tags from the image.

With no parameters, it retrieves a list of array references, each one containing a name and value β€” AKA all the tags in the image πŸ”₯

# get a list of ( [ name1 => value1 ], [ name2 => value2 ] ... )
my @alltags = $img->tags;
print $_->[0], ":", $_->[1], "\n" for @all_tags;

# or put it in a hash, but this will lose duplicates
my %alltags = map @$_, $img->tags;

In scalar context this returns the number of tags:

my $num_tags = $img->tags;

Or you can get all tag values for the given name:

my @namedtags = $img->tags(name => $name);

In scalar context this returns the first tag of that name:

my $firstnamed = $img->tags(name => $name);

Or a given code:

my @tags = $img->tags(code=>$code);

addtag() βž•

You can add tags with the addtag() method, either by name:

my $index = $img->addtag(name=>$name, value=>$value);

or by code:

my $index = $img->addtag(code=>$code, value=>$value);
⚠️ Setting tags by code is deprecated. If you actually have a use for this, please open an issue β€” otherwise maybe don't, bestie 😭

deltag() πŸ—‘οΈ

You can remove tags with the deltag() method, either by index:

$img->deltag(index=>$index);

or by name:

$img->deltag(name=>$name);

or by code:

$img->deltag(code=>$code);

In each case deltag() returns the number of tags deleted β€” a cute little receipt for how much you cleaned up 🧹✨

⚠️ Setting or deleting tags by code is deprecated. If you have a use for this, please open an issue.

settag() πŸ”

settag() replaces any existing tags with a new tag. This is literally equivalent to calling deltag() then addtag(). Same energy, one call πŸ’…


🌈 Common Tags πŸ¦‹

Many tags are only meaningful for one format. GIF looping information is pretty useless for a JPEG, for example β€” it's not even invited to that party πŸ™ˆ So lots of tags are set by only a single reader or used by a single writer. For the complete list of format-specific tags, see Imager::Files.

Since tags are a relatively new addition, their use is not wide spread β€” but eventually we hope to have all the readers for the various formats set some standard information. Manifesting it 🌟

  • i_xres, i_yres β€” the spatial resolution of the image in pixels per inch. If the image format uses a different scale, e.g. pixels per meter, then this value is converted for you. A floating point number stored as a string, fancy πŸ’–
# our image was generated as a 300 dpi image
$img->settag(name => 'i_xres', value => 300);
$img->settag(name => 'i_yres', value => 300);

# 100 pixel/cm for a TIFF image
$img->settag(name => 'tiff_resolutionunit', value => 3); # RESUNIT_CENTIMETER
# convert to pixels per inch, Imager will convert it back
$img->settag(name => 'i_xres', value => 100 * 2.54);
$img->settag(name => 'i_yres', value => 100 * 2.54);
  • i_aspect_only β€” if this is non-zero, then the values in i_xres and i_yres are treated as a ratio only. If the image format doesn't support aspect ratios, then this is scaled so the smaller value is 72 DPI. Ratio girl summer πŸŽ€
  • i_incomplete β€” if this tag is present, then the whole image could not be read 😭 Heads up though: this isn't implemented for all images yet, and may not be.
  • i_lines_read β€” if i_incomplete is set, then this tag may be set to the number of scan lines successfully read from the file. Super useful for deciding whether an image is even worth processing, iykyk πŸ‘‘
  • i_format β€” the file format this file was read from.
  • i_background β€” used when writing an image with an alpha channel to a file format that doesn't support alpha channels. The write method will convert a normal color specification like "#FF0000" into a color object for you, but if you set this as a tag you'll need to format it like "color("red","green","blue")", eg color(255,0,0). Yeah it's a little extra, but that's the vibe πŸ’…
  • i_comment β€” used when reading or writing several image formats. If the format has only one text field, it will be read into the i_comment tag or written to the file. One text field, one icon 🫢

🎨 Quantization options 🌸

These options can be specified when calling to_paletted() in Imager::ImageTypes, write_multi() for GIF files, when writing a single image with the gifquant option set to gen, or for direct calls to i_writegif_gen() and i_writegif_callback(). So many doorways, same options πŸšͺ✨

  • colors β€” an arrayref of colors that are fixed. Note that some color generators will ignore this (rude). If this is supplied, it will be filled with the color table generated for the image.
  • transp β€” the type of transparency processing to perform for images with an alpha channel where the output format doesn't have a proper alpha channel (eg. GIF). This can be any of:
    • none β€” no transparency processing is done. (default)
    • threshold β€” pixels more transparent than tr_threshold are rendered as transparent.
    • errdiff β€” an error diffusion dither is done on the alpha channel. Note that this is independent of the translation performed on the color channels, so some combinations may cause undesired artifacts 😬
    • ordered β€” the ordered dither specified by tr_orddith is performed on the alpha channel.

This will only be used if the image has an alpha channel, and if there's space in the palette for a transparency color. Fingers crossed bestie 🀞

  • tr_threshold β€” the highest alpha value at which a pixel will be made transparent when transp is 'threshold'. (0-255, default 127)
  • tr_errdiff β€” the type of error diffusion to perform on the alpha channel when transp is errdiff. This can be any defined error diffusion type except for custom (see errdiff below).
  • tr_orddith β€” the type of ordered dither to perform on the alpha channel when transp is 'ordered'. Possible values are:
    • random β€” a semi-random map is used. The map is the same each time. (semi-random but consistent, we love a reliable queen 🌈)
    • dot8 β€” 8x8 dot dither.
    • dot4 β€” 4x4 dot dither
    • hline β€” horizontal line dither.
    • vline β€” vertical line dither.
    • /line, slashline β€” diagonal line dither
    • \line, backline β€” diagonal line dither
    • tiny β€” dot matrix dither (currently the default). This is probably the best for displays (like web pages) πŸ’»βœ¨
    • custom β€” a custom dither matrix is used β€” see tr_map.
  • tr_map β€” when tr_orddith is custom, this defines an 8 x 8 matrix of integers representing the transparency threshold for pixels corresponding to each position. This should be a 64 element array where the first 8 entries correspond to the first row of the matrix. Values should be between 0 and 255. Build it carefully, bestie 🧚
  • make_colors β€” defines how the quantization engine will build the palette(s). Currently this is ignored if translate is giflib, but that may change. Possible values are:
    • none β€” only colors supplied in 'colors' are used.
    • webmap β€” the web color map is used (need URL here.)
    • addi β€” the original code for generating the color map (Addi's code) is used.
    • mediancut β€” uses a median-cut algorithm, faster than addi, but not as good a result.
    • mono, monochrome β€” a fixed black and white palette, suitable for producing bi-level images (eg. facsimile)
    • gray, gray4, gray16 β€” make fixed gray palette with 256, 4 or 16 entries respectively.

Other methods may be added in the future. Watch this space πŸ‘€

  • colors β€” an arrayref containing Imager::Color objects, which represents the starting set of colors to use in translating the images. webmap will ignore this. On return the final colors used are copied back into this array (which is expanded if necessary). Yes, this is a different colors from the one above β€” iykyk, they're both iconic in their own way πŸ’…
  • max_colors β€” the maximum number of colors to use in the image.
  • translate β€” the method used to translate the RGB values in the source image into the colors selected by make_colors. Note that make_colors is ignored when translate is giflib.

Possible values are:

  • giflib β€” this is a historical equivalent for closest that also forces make_colors to mediancut.
  • closest β€” the closest color available is used.
  • perturb β€” the pixel color is modified by perturb, and the closest color is chosen.
  • errdiff β€” an error diffusion dither is performed. If the supplied (or generated) palette contains only grays, the source colors are converted to gray before error diffusion is performed.

It's possible other translate values will be added.

  • errdiff β€” the type of error diffusion dither to perform. These values (except for custom) can also be used in tr_errdif.
    • floyd β€” Floyd-Steinberg dither
    • jarvis β€” Jarvis, Judice and Ninke dither
    • stucki β€” Stucki dither
    • custom β€” custom. If you use this you must also set errdiff_width, errdiff_height and errdiff_map. No skipping steps πŸ”₯
  • errdiff_width, errdiff_height, errdiff_orig, errdiff_map β€” when translate is errdiff and errdiff is custom, these define a custom error diffusion map. errdiff_width and errdiff_height define the size of the map in the arrayref in errdiff_map. errdiff_orig is an integer which indicates the current pixel position in the top row of the map. Custom map squad, assemble 🫢
  • "perturb" β€” okay so when translate is "perturb", this is the magnitude of the random bias that gets applied to each channel of the pixel before it gets looked up in the color table. slay.

✨ INITIALIZATION ✨

This documents the Imager initialization function, which you will almost never need to call. like, genuinely, almost never.

🌟 init() 🌟

This is a function, not a method.

This function is a mess, bestie β€” it can take the following named parameters:

  • "log" β€” the name of a log file to log Imager's actions to. Not all actions are logged, but the debugging memory allocator does log allocations here. This is ignored if Imager has been built without logging support. Preferably use the open_log() method instead.
  • "loglevel" β€” the maximum level of message to log. Default: 1.
  • "warn_obsolete" β€” if this is non-zero, then Imager will warn when you attempt to use obsoleted parameters or functionality. This currently only includes the old GIF output options instead of tags.
  • "t1log" β€” if non-zero, then T1lib will be configured to produce a log file. This will fail if there are any existing T1lib font objects.

Example:

Imager::init(log => 'trace.log', loglevel => 9);

πŸ“ LOGGING METHODS πŸ“

Imager can open an internal log to send debugging information to. This log is extensively used in Imager's tests, but you're unlikely to use it otherwise.

If Imager has been built with logging disabled, the methods fail quietly.

πŸŽ€ open_log() πŸŽ€

Open the Imager debugging log file.

  • "log" β€” the file name to log to. If this is undef, logging information is sent to the standard error stream.
  • "loglevel" β€” the level of logging to produce. Default: 1.

Returns a true value if the log file was opened successfully.

# send debug output to test.log
Imager->open_log(log => "test.log");

# send debug output to stderr
Imager->open_log();

πŸ¦‹ close_log() πŸ¦‹

Close the Imager debugging log file and disable debug logging.

No parameters.

Imager->close_log();

🌸 log() 🌸

Imager->log($message)
Imager->log($message, $level)

This method does not use named parameters.

The default for $level is 1.

Send a message to the debug log.

Imager->log("My code got here!");

⭐ is_logging() ⭐

Returns a true value if logging is enabled.

πŸ’– AUTHOR πŸ’–

Tony Cook <tonyc@cpan.org>, Arnar M. Hrafnkelsson

πŸ‘€ SEE ALSO πŸ‘€


and that's the whole page, bestie 🫢 the footer is giving source/version + date realness: perl v5.42.3, 2026-08-19, page Imager...eTypes(3pm) β€” mwah πŸ’…βœ¨

πŸ“¦ where this page comes from