Imager...mations(3pm)

Manual page: Imager::Transformations(3pm) ยท User Contributed Perl Documentation ๐Ÿซถ

๐ŸŒธ NAME ๐ŸŒธ

Imager::Transformations โ€” Simple transformations of one image into another. ๐Ÿ’–

โœจ SYNOPSIS โœจ

okay bestie, hereโ€™s the quick-start shape of it all:

use Imager;

$newimg = $img->copy();

$newimg = $img->scale(xpixels=>400, qtype => 'mixing');
$newimg = $img->scale(xpixels=>400, ypixels=>400);
$newimg = $img->scale(xpixels=>400, ypixels=>400, type=>'min');
$newimg = $img->scale(scalefactor=>0.25);

$newimg = $img->scaleX(pixels=>400);
$newimg = $img->scaleX(scalefactor=>0.25);
$newimg = $img->scaleY(pixels=>400);
$newimg = $img->scaleY(scalefactor=>0.25);

$newimg = $img->crop(left=>50, right=>100, top=>10, bottom=>100);
$newimg = $img->crop(left=>50, top=>10, width=>50, height=>90);

$dest->paste(left=>40,top=>20,img=>$logo);

$img->rubthrough(src=>$srcimage,tx=>30, ty=>50);
$img->rubthrough(src=>$srcimage,tx=>30, ty=>50,
                 src_minx=>20, src_miny=>30,
                 src_maxx=>20, src_maxy=>30);

$img->compose(src => $src, tx => 30, ty => 20, combine => 'color');
$img->compose(src => $src, tx => 30, ty => 20, combine => 'color');
              mask => $mask, opacity => 0.5);

$img->flip(dir=>"h");       # horizontal flip
$img->flip(dir=>"vh");      # vertical and horizontal flip
$newimg = $img->copy->flip(dir=>"v"); # make a copy and flip it vertically

my $rot20 = $img->rotate(degrees=>20);
my $rotpi4 = $img->rotate(radians=>3.14159265/4);

# Convert image to gray
$new = $img->convert(preset=>'grey');

# Swap red/green channel
$new = $img->convert(matrix=>[ [ 0, 1, 0 ],
                               [ 1, 0, 0 ],
                               [ 0, 0, 1 ] ]);

# build an image using channels from multiple input images
$new = $img->combine(src => [ $im1, $im2, $im3 ]);
$new = $img->combine(src => [ $im1, $im2, $im3 ],
                     channels => [ 2, 1, 0 ]);

# limit the range of red channel from 0..255 to 0..127
@map = map { int( $_/2 } 0..255;
$img->map( red=>\@map );

# Apply a Gamma of 1.4
my $gamma = 1.4;
my @map = map { int( 0.5 + 255*($_/255)**$gamma ) } 0..255;
$img->map(all=>\@map);  # inplace conversion

๐Ÿ’… DESCRIPTION ๐Ÿ’…

okay so hereโ€™s the whole vibe: the methods described in Imager::Transformations fall into two categories, bestie. Either they take an existing image and modify it in place, or they return a modified copy. โœจ

Functions that modify inplace are flip(), paste(), rubthrough() and compose(). If the original is to be left intact itโ€™s possible to make a copy and alter the copy:

$flipped = $img->copy()->flip(dir=>'h');

๐Ÿฆ‹ Image copying/resizing/cropping/rotating ๐Ÿฆ‹

A list of the transformations that do not alter the source image follows:

๐ŸŽ€ copy() ๐ŸŽ€

To create a copy of an image use the copy() method. This is useful if you want to keep an original after doing something that changes the image.

$newimg = $orig->copy();

๐Ÿš scale() ๐Ÿš

To scale an image so proportions are maintained use the $img->scale() method. If you give either a xpixels or ypixels parameter they will determine the width or height respectively. If both are given the one resulting in a larger image is used, unless you set the type parameter to 'min'. example: $img is 700 pixels wide and 500 pixels tall.

$newimg = $img->scale(xpixels=>400); # 400x285
$newimg = $img->scale(ypixels=>400); # 560x400

$newimg = $img->scale(xpixels=>400,ypixels=>400); # 560x400
$newimg = $img->scale(xpixels=>400,ypixels=>400,type=>'min'); # 400x285

$newimg = $img->scale(xpixels=>400, ypixels=>400),type=>'nonprop'); # 400x400

$newimg = $img->scale(scalefactor=>0.25); 175x125
$newimg = $img->scale(); # 350x250

If you want to create low quality previews of images you can pass qtype=>'preview' to scale and it will use nearest neighbor sampling instead of filtering. It is much faster but also generates worse looking images โ€” especially if the original has a lot of sharp variations and the scaled image is by more than 3-5 times smaller than the original.

  • xpixels, ypixels โ€” desired size of the scaled image. The type parameter controls whether the larger or smaller of the two possible sizes is chosen, or if the image is scaled non-proportionally.
  • constrain โ€” an Image::Math::Constrain object defining the way in which the image size should be constrained.
  • scalefactor โ€” if none of xpixels, ypixels, xscalefactor, yscalefactor or constrain is supplied then this is used as the ratio to scale by. Default: 0.5.
  • xscalefactor, yscalefactor โ€” if both are supplied then the image is scaled as per these parameters, whether this is proportionally or not. New in Imager 0.54.
  • type โ€” when both xpixels and ypixels are supplied and do not scale the image proportionally type controls whether the larger or smaller of the two possible sizes is chosen, or whether the resulting image is stretched.

Possible values are:

  • min โ€” the smaller of the two possible sizes is chosen.
  • max โ€” the larger of the two possible sizes is chosen. This is the default.
  • nonprop โ€” allow non-proportional scaling.

scale() will fail if type is set to some other value.

For example, if the original image is 400 pixels wide by 200 pixels high and xpixels is set to 300, and ypixels is set to 160:

# $image is 400x200
my $scaled = $image->scale(xpixels => 300, ypixels => 160, type => $type);

then scaling to 300x160 would distort the message, making it look stretched vertically.

Scaling to 300 x 150, based on xpixels or 320 x 160 based on ypixels prevents any stretching, preserving a ratio of two to one for width to height.

When type is min the result is the smaller 300 x 150 image, when type is max the result is the larger 320 x 160 image. nonprop doesnโ€™t attempt to scale proportionally at all, producing a 300 x 160 image.

  • qtype โ€” defines the quality of scaling performed. Possible values are:
    • normal โ€” high quality scaling. This is the default.
    • preview โ€” lower quality. When scaling down this will skip input pixels, eg. scaling by 0.5 will skip every other pixel. When scaling up this will duplicate pixels.
    • mixing โ€” implements the mixing algorithm implemented by pnmscale. This retains more detail when scaling down than normal. When scaling down this proportionally accumulates sample data from the pixels, resulting in a proportional mix of all of the pixels. When scaling up this will mix pixels when the sampling grid crosses a pixel boundary but will otherwise copy pixel values.

scale() will fail if qtype is set to some other value.

preview is faster than mixing which is much faster than normal.

To scale an image on a given axis without maintaining proportions, it is best to call the scaleX() and scaleY() methods with the required dimensions. eg.

my $scaled = $img->scaleX(pixels=>400)->scaleY(pixels=>200);

From Imager 0.54 you can scale without maintaining proportions either by supplying both the xscalefactor and yscalefactor arguments:

my $scaled = $img->scale(xscalefactor => 0.5, yscalefactor => 0.67);

or by supplying xpixels and ypixels and setting type to 'nonprop':

my $scaled = $im->scale(xpixels => 200, ypixels => 200, type => 'nonprop');

Returns a new scaled image on success. The source image is not modified. ๐ŸŒˆ

Returns false on failure, check the errstr() method for the reason for failure.

๐Ÿšจ A mandatory warning is produced if scale() is called in void context.
# setup
my $image = Imager->new;
$image->read(file => 'somefile.jpg')
  or die $image->errstr;

# all full quality unless indicated otherwise
# half the size:
my $half = $image->scale;

# double the size
my $double = $image->scale(scalefactor => 2.0);

# so a 400 x 400 box fits in the resulting image:
my $fit400x400inside = $image->scale(xpixels => 400, ypixels => 400);
my $fit400x400inside2 = $image->scale(xpixels => 400, ypixels => 400,
                                      type=>'max');

# fit inside a 400 x 400 box
my $inside400x400 = $image->scale(xpixels => 400, ypixels => 400,
                            type=>'min');

# make it 400 pixels wide or high
my $width400 = $image->scale(xpixels => 400);
my $height400 = $image->scale(ypixels => 400);

# low quality scales:
# to half size
my $low = $image->scale(qtype => 'preview');

# mixing method scale
my $mixed = $image->scale(qtype => 'mixing', scalefactor => 0.1);

# using an Image::Math::Constrain object
use Image::Math::Constrain;
my $constrain = Image::Math::Constrain->new(800, 600);
my $scaled = $image->scale(constrain => $constrain);

# same as Image::Math::Constrain version
my $scaled2 = $image->scale(xpixels => 800, ypixels => 600, type => 'min');

๐ŸŒธ scaleX() ๐ŸŒธ

scaleX() will scale along the X dimension, return a new image with the new width:

my $newimg = $img->scaleX(pixels=>400); # 400x500
$newimg = $img->scaleX(scalefactor=>0.25) # 175x500
  • scalefactor โ€” the amount to scale the X axis. Ignored if pixels is provided. Default: 0.5.
  • pixels โ€” the new width of the image.

Returns a new scaled image on success. The source image is not modified. ๐Ÿ’–

Returns false on failure, check the errstr() method for the reason for failure.

๐Ÿšจ A mandatory warning is produced if scaleX() is called in void context.

๐Ÿฆ‹ scaleY() ๐Ÿฆ‹

scaleY() will scale along the Y dimension, return a new image with the new height:

$newimg = $img->scaleY(pixels=>400); # 700x400
$newimg = $img->scaleY(scalefactor=>0.25) # 700x125
  • scalefactor โ€” the amount to scale the Y axis. Ignored if pixels is provided. Default: 0.5.
  • pixels โ€” the new height of the image.

She's giving "new image, who dis" ๐Ÿ’… โ€” on success you get a brand new scaled image back, and the source image is not modified. Not one pixel. She's untouched, bestie, we don't do that here.

If it flops you get false, and then you go check the errstr() method for the reason it failed ๐Ÿ˜ญ (she will tell you why, but only if you ask).

๐Ÿšจ real talk: a mandatory warning is produced if scaleY() is called in void context. Mandatory. It's happening. You can't dodge it.

๐Ÿงฎ scale_calculate() ๐Ÿงฎ

This one does the exact same math that the scale() method does to work out the scaling factors from the parameters you hand her โ€” except she doesn't touch an image, she just tells you the numbers โœจ

scale_calculate() can be called as an object method or as a class method. Versatile queen.

It takes the following parameters on top of scale():

  • "width", "height" โ€” the image width and height to base the scaling on. Required if scale_calculate() is called as a class method. If you call it as an object method instead, these default to the image width and height respectively.

You'd use scale_calculate() as a class method when you're generating an HTML IMG tag, for example ๐Ÿ‘€

Returns an empty list on failure ๐Ÿซ 

Returns a list containing horizontal scale factor, vertical scale factor, new width, new height, on success:

  my ($x_scale, $y_scale, $new_width, $new_height) =
        Imager->scale_calculate(width => 1024, height => 768,
                                ypixels => 180, type => 'min');

  my ($x_scale, $y_scale, $new_width, $new_height) =
        $img->scale_calculate(xpixels => 200, type => 'min');

โœ‚๏ธ crop() โœ‚๏ธ

Another way to resize an image is to crop it โ€” and honestly? It's such a vibe. The parameters to crop() are the edges of the area you want in the returned image, where the right and bottom edges are non-inclusive (iykyk, she's not counting those). Omit a parameter and a default just slides in.

crop() returns the cropped image and does not modify the source image ๐Ÿ’–

The possible parameters are:

  • "left" โ€” the left edge of the area to be cropped. Default: 0
  • "top" โ€” the top edge of the area to be cropped. Default: 0
  • "right" โ€” the right edge of the area to be cropped. Default: right edge of image.
  • "bottom" โ€” the bottom edge of the area to be cropped. Default: bottom edge of image.
  • "width" โ€” width of the crop area. Ignored if both "left" and "right" are supplied. Centered on the image if neither "left" nor "right" are supplied.
  • "height" โ€” height of the crop area. Ignored if both "top" and "bottom" are supplied. Centered on the image if neither "top" nor "bottom" are supplied.

For example:

  # these produce the same image
  $newimg = $img->crop(left=>50, right=>100, top=>10, bottom=>100);
  $newimg = $img->crop(left=>50, top=>10, width=>50, height=>90);
  $newimg = $img->crop(right=>100, bottom=>100, width=>50, height=>90);

  # and the following produce the same image
  $newimg = $img->crop(left=>50, right=>100);
  $newimg = $img->crop(left=>50, right=>100, top=>0,
                       bottom=>$img->getheight);

  # grab the top left corner of the image
  $newimg = $img->crop(right=>50, bottom=>50);

You can also specify width and height parameters, which will produce a new image cropped from the center of the input image, with the given width and height ๐ŸŒธ

  $newimg = $img->crop(width=>50, height=>50);

If you supply "left", "width" and "right" values, the "right" value will be ignored. Same energy with "top", "height" and "bottom" โ€” the "bottom" value gets ignored.

The edges of the cropped area default to the edges of the source image, for example:

  # a vertical bar from the middle from top to bottom
  $newimg = $img->crop(width=>50);

  # the right half
  $newimg = $img->crop(left=>$img->getwidth() / 2);
โš ๏ธ if the resulting image would have zero width or height, then crop() returns false and $img->errstr is an appropriate error message. No zero-sized images on her watch.
๐Ÿšจ and yes โ€” a mandatory warning is produced if crop() is called in void context. Same rule as before, bestie.

๐Ÿ”„ rotate() ๐Ÿ”„

Use the rotate() method to rotate an image. It returns a new, rotated image โ€” source stays iconic and untouched โœจ

To rotate by an exact amount in degrees or radians, use the 'degrees' or 'radians' parameter:

  my $rot20 = $img->rotate(degrees=>20);
  my $rotpi4 = $img->rotate(radians=>3.14159265/4);

Exact image rotation uses the same underlying transformation engine as the matrix_transform() method (see Imager::Engines) ๐Ÿงš

You can also supply a "back" argument which acts as a background color for the areas of the image with no samples available (outside the rectangle of the source image). This can be either an Imager::Color or Imager::Color::Float object. And ngl this is not about mixing transparent pixels in the middle of the source image โ€” it's only used for pixels where there is no corresponding pixel in the source image. Periodt.

To rotate in steps of 90 degrees, use the 'right' parameter:

  my $rotated = $img->rotate(right=>270);

Rotations are clockwise for positive values ๐Ÿ’ซ

Parameters:

  • "right" โ€” rotate by an exact multiple of 90 degrees, specified in degrees.
  • "radians" โ€” rotate by an angle specified in radians.
  • "degrees" โ€” rotate by an angle specified in degrees.
  • "back" โ€” for "radians" and "degrees" this is the color used for the areas not covered by the original image. For example, the corners of an image rotated by 45 degrees.

This can be either an Imager::Color object, an Imager::Color::Float object or any parameter that Imager can convert to a color object, see "Color Parameters" in Imager::Draw for details.

This is not mixed transparent pixels in the middle of the source image, it is only used for pixels where there is no corresponding pixel in the source image.

Default: transparent black.

  # rotate 45 degrees clockwise,
  my $rotated = $img->rotate(degrees => 45);

  # rotate 10 degrees counter-clockwise
  # set pixels not sourced from the original to red
  my $rotated = $img->rotate(degrees => -10, back => 'red');

๐Ÿ“ trim() ๐Ÿ“

Returns a cropped version of the original image, cropped of its border pixels โ€” based on either transparent pixels, or pixels that match any of a set of provided colors. It's giving "gimme just the good part" ๐Ÿ’…

If you just want the number of pixels to be cropped on each side, you can use the "trim_rect()" method instead ๐Ÿ‘‘

โš ๏ธ if the supplied parameters would result in the entire image being cropped, then a single pixel image is returned from the top left of the source image. Tiny icon energy.

To trim just on fully transparent pixels:

   my $trimmed = $img->trim();

To trim pixels with less than 1% coverage:

   my $trimmed = $img->trim(alpha => 0.01);

To trim based on automatically determined colors and fully transparent pixels:

   my $trimmed = $img->trim(auto => 1);

To trim a black border:

  my $trimmed = $img->trim(colors => [ "#000" ]);

Parameters:

  • "alpha" โ€” any pixels with less than or equal coverage to this value will be treated as part of the border to be cropped. This is always expressed as a fraction, so alpha => 1.0 will treat all pixels as part of the border ๐Ÿ˜ณ Default: 0 (fully transparent pixels are part of the border).
  • "auto" โ€” automatically select colors to crop on. Possible values:
    • 1 โ€” a "best" mechanism is selected, this is currently the "center" method, but it subject to change.
    • "center", "centre" โ€” the pixels at the center of each side of the image are used.
  • "tolerance" โ€” used by the "auto" mechanism to control the range of pixel colors to be accepted as part of the border. Default: 0.01.
  • "colors" โ€” either an Imager::TrimColorList object or a reference to an array of color entries to be considered part of the border. Code like:
    my $trimmed = $img->trim(colors => [ LIST ]);

results in a temporary Imager::TrimColorList being produced like:

    my $trimmed = $img->trim(colors => Imager::TrimColorList->new( LIST ));
๐Ÿ’€ "colors" and "auto" exclude each other โ€” only one or the other can be supplied. Pick a lane, babe.

๐Ÿ“ trim_rect() ๐Ÿ“

Returns a list of the number of columns and rows that would be removed from each side if trim() was called. It's the receipts, not the makeover ๐Ÿ’–

   my ($left, $top, $right, $bottom) = $img->trim_rect();

If the entire image matches the trim parameters, then $left will be the width of the image and $top will be the height of the image.

Accepts the same parameters as "trim()".


๐Ÿฆ‹ IMAGE PASTING/FLIPPING ๐Ÿฆ‹

A list of the transformations that alter the source image follows ๐Ÿ‘€ (yes, these ones actually change the source โ€” read the room):

๐ŸŽ€ paste() ๐ŸŽ€

To copy an image onto another image, use the paste() method:

  $dest->paste(left=>40, top=>20, src=>$logo);

That copies the entire $logo image onto the $dest image so that the upper left corner of the $logo image is at (40,20) ๐ŸŒˆ

Parameters:

  • "src", "img" โ€” the source image. "src" added for compatibility with rubthrough().
  • "left", "top" โ€” position in output of the top left of the pasted image. Default: (0,0)
  • "src_minx", "src_miny" โ€” the top left corner in the source image to start the paste from. Default: (0, 0)
  • "src_maxx", "src_maxy" โ€” the bottom right in the source image of the sub image to paste. This position is non inclusive. Default: bottom right corner of the source image.
  • "width", "height" โ€” if the corresponding src_maxx or src_maxy is not defined then width or height is used for the width or height of the sub image to be pasted.
  # copy the 20x20 pixel image from (20,20) in $src_image to (10,10) in $img
  $img->paste(src=>$src_image,
              left => 10, top => 10,
              src_minx => 20, src_miny => 20,
              src_maxx => 40, src_maxx => 40);
๐Ÿฉท if the source image has an alpha channel and the target doesn't, then the source is treated as if composed onto a black background.
๐Ÿฉท and if the source image is color and the target is gray scale, the source is treated as if run through convert(preset=>'gray').

๐Ÿซถ rubthrough() ๐Ÿซถ

A more complicated way of blending images is where one image is put 'over' the other with a certain amount of opaqueness. The method that does this is rubthrough(). โœจ

$img->rubthrough(src=>$overlay,
                 tx=>30,       ty=>50,
                 src_minx=>20, src_miny=>30,
                 src_maxx=>20, src_maxy=>30);

Thatโ€™s the whole vibe, bestie: it takes the sub image defined by $overlay and [src_minx,src_maxx)[src_miny,src_maxy) and overlays it on top of $img with the upper left corner at (30,50). You can rub 2 or 4 channel images onto a 3 channel image, or a 2 channel image onto a 1 channel image. The last channel is used as an alpha channel. To add an alpha channel to an image see convert(). ๐Ÿ’–

Parameters:

  • tx, ty โ€” location in the target image ($self) to render the top left corner of the source.
  • src_minx, src_miny โ€” the top left corner in the source to transfer to the target image. Default: (0, 0).
  • src_maxx, src_maxy โ€” the bottom right in the source image of the sub image to overlay. This position is non inclusive. Default: bottom right corner of the source image.
# overlay all of $source onto $targ
$targ->rubthrough(tx => 20, ty => 25, src => $source);

# overlay the top left corner of $source onto $targ
$targ->rubthrough(tx => 20, ty => 25, src => $source,
                  src_maxx => 20, src_maxy => 20);

# overlay the bottom right corner of $source onto $targ
$targ->rubthrough(tx => 20, ty => 30, src => $src,
                  src_minx => $src->getwidth() - 20,
                  src_miny => $src->getheight() - 20);

rubthrough() returns true on success. On failure check $target->errstr for the reason for failure. โœจ


๐Ÿ’… compose() ๐Ÿ’…

Draws the source image over the target image, with the source alpha channel modified by the optional mask and the opacity. Itโ€™s giving โ€œlayers in a paint appโ€ energy, fr fr. ๐ŸŽ€

$img->compose(src=>$overlay,
              tx=>30,       ty=>50,
              src_minx=>20, src_miny=>30,
              src_maxx=>20, src_maxy=>30,
              mask => $mask, opacity => 0.5);

That will take the sub image defined by $overlay and [src_minx,src_maxx)[src_miny,src_maxy) and overlay it on top of $img with the upper left corner at (30,50). You can rub 2 or 4 channel images onto a 3 channel image, or a 2 channel image onto a 1 channel image. ๐Ÿ’ซ

Parameters:

  • src โ€” the source image to draw onto the target. Required.
  • tx, ty โ€” location in the target image ($self) to render the top left corner of the source. These can also be supplied as left and right. Default: (0, 0).
  • src_minx, src_miny โ€” the top left corner in the source to transfer to the target image. Default: (0, 0).
  • src_maxx, src_maxy โ€” the bottom right in the source image of the sub image to overlay. This position is non inclusive. Default: bottom right corner of the source image.
  • mask โ€” a mask image. The first channel of this image is used to modify the alpha channel of the source image. This can be used to mask out portions of the source image. Where the first channel is zero none of the source image will be used, where the first channel is maximum the full alpha of the source image will be used, as further modified by the opacity.
  • opacity โ€” further modifies the alpha channel of the source image, in the range 0.0 to 1.0. Default: 1.0.
  • combine โ€” the method to combine the source pixels with the target. See the combine option documentation in Imager::Fill. Default: normal.

Calling compose() with no mask, combine set to normal, opacity set to 1.0 is equivalent to calling rubthrough(). No cap. ๐Ÿซถ

compose() is intended to produce similar effects to layers in interactive paint software.

# overlay all of $source onto $targ
$targ->compose(tx => 20, ty => 25, src => $source);

# overlay the top left corner of $source onto $targ
$targ->compose(tx => 20, ty => 25, src => $source,
                  src_maxx => 20, src_maxy => 20);

# overlay the bottom right corner of $source onto $targ
$targ->compose(tx => 20, ty => 30, src => $src,
                  src_minx => $src->getwidth() - 20,
                  src_miny => $src->getheight() - 20);

compose() returns true on success. On failure check $target->errstr for the reason for failure. ๐Ÿ’€


๐Ÿ”„ flip() ๐Ÿ”„

An inplace horizontal or vertical flip is possible by calling the flip() method. If the original is to be preserved itโ€™s possible to make a copy first. The only parameter it takes is the dir parameter, which can take the values h, v, vh and hv. Slay. ๐ŸŒธ

$img->flip(dir=>"h");       # horizontal flip
$img->flip(dir=>"vh");      # vertical and horizontal flip
$nimg = $img->copy->flip(dir=>"v"); # make a copy and flip it vertically

flip() returns true on success. On failure check $img->errstr for the reason for failure. โœจ


โœจ Color transformations โœจ

๐ŸŽจ convert() ๐ŸŽจ

You can use the convert method to transform the color space of an image using a matrix. For ease of use some presets are provided. This is lowkey iconic for color glow-ups. ๐Ÿ’…

The convert method can be used to:

  • convert an RGB or RGBA image to gray scale.
  • convert a gray scale image to RGB.
  • extract a single channel from an image.
  • set a given channel to a particular value (or from another channel).

The currently defined presets are:

  • gray, grey โ€” converts an RGBA image into a gray scale image with alpha channel, or an RGB image into a gray scale image without an alpha channel. This weights the RGB channels at 22.2%, 70.7% and 7.1% respectively.
  • noalpha โ€” removes the alpha channel from a 2 or 4 channel image. An identity for other images. Warning: this removes the alpha channel without applying it. ๐Ÿ˜ญ
  • red, channel0 โ€” extracts the first channel of the image into a single channel image.
  • green, channel1 โ€” extracts the second channel of the image into a single channel image.
  • blue, channel2 โ€” extracts the third channel of the image into a single channel image.
  • alpha โ€” extracts the alpha channel of the image into a single channel image. If the image has 1 or 3 channels (assumed to be gray scale or RGB) then the resulting image will be all white.
  • rgb โ€” converts a gray scale image to RGB, preserving the alpha channel if any.
  • addalpha โ€” adds an alpha channel to a gray scale or RGB image. Preserves an existing alpha channel for a 2 or 4 channel image.

For example, to convert an RGB image into a gray scale image:

$new = $img->convert(preset=>'grey'); # or gray

or to convert a gray scale image to an RGB image:

$new = $img->convert(preset=>'rgb');

The presets arenโ€™t necessarily simple constants in the code โ€” some are generated based on the number of channels in the input image. ๐Ÿงš

If you want to perform some other color transformation, you can use the 'matrix' parameter.

For each output pixel the following matrix multiplication is done:

| channel[0] |   | $c00, ...,  $c0k |   | inchannel[0] |
|    ...     | = |       ...        | x |     ...      |
| channel[k] |   | $ck0, ..., $ckk  |   | inchannel[k] |
                                                                1

Where k = $img->getchannels()-1.

So if you want to swap the red and green channels on a 3 channel image:

$new = $img->convert(matrix=>[ [ 0, 1, 0 ],
                               [ 1, 0, 0 ],
                               [ 0, 0, 1 ] ]);

or to convert a 3 channel image to gray scale using equal weightings:

$new = $img->convert(matrix=>[ [ 0.333, 0.333, 0.334 ] ])

Convert a 2 channel image (gray scale with alpha) to an RGBA image with the gray converted to the specified RGB color:

# set (RGB) scaled on the grey scale portion and copy the alpha
# channel as is
my $colored = $gray->convert(matrix=>[ [ ($red/255),   0 ],
                                       [ ($green/255), 0 ],
                                       [ ($blue/255),  0 ],
                                       [ 0,            1 ],
                                     ]);

To convert a 3 channel image to a 4 channel image with a 50 percent alpha channel:

my $withalpha = $rgb->convert(matrix =>[ [ 1, 0, 0, 0 ],
                                         [ 0, 1, 0, 0 ],
                                         [ 0, 0, 1, 0 ],
                                         [ 0, 0, 0, 0.5 ],
                                       ]);

๐Ÿงฉ combine() ๐Ÿงฉ

Combine channels from one or more input images into a new image. Itโ€™s basically friendship bracelets but for channels. ๐Ÿซถ

Parameters:

  • src โ€” a reference to an array of input images. There must be at least one input image. A given image may appear more than once in src.
  • channels โ€” a reference to an array of channels corresponding to the source images. If channels is not supplied then the first channel from each input image is used. If the array referenced by channels is shorter than that referenced by src then the first channel is used from the extra images.
# make an rgb image from red, green, and blue images
my $rgb = Imager->combine(src => [ $red, $green, $blue ]);

# convert a BGR image into RGB
my $rgb = Imager->combine(src => [ $bgr, $bgr, $bgr ],
                          channels => [ 2, 1, 0 ]);

# add an alpha channel from another image
my $rgba = Imager->combine(src => [ $rgb, $rgb, $rgb, $alpha ],
                   channels => [ 0, 1, 2, 0 ]);

๐ŸŒˆ Color Mappings ๐ŸŒˆ

๐Ÿ—บ๏ธ map() ๐Ÿ—บ๏ธ

You can use the map method to map the values of each channel of an image independently using a list of look-up tables. Itโ€™s important to realize that the modification is made inplace. The function simply returns the input image again or undef on failure. ๐ŸŽ€

Each channel is mapped independently through a look-up table with 256 entries. The elements in the table should not be less than 0 and not greater than 255. If they are out of the 0..255 range they are clamped to the range. If a table does not contain 256 entries it is silently ignored. ๐Ÿ’–

k so back to channel mapping, bestie, because this part is chef's kiss ๐ŸŽ€

๐ŸŒธ mapping single channels ๐ŸŒธ

You can map single channels by naming them and handing over the mapping table. The channel names are literally red, green, blue, alpha. That's the whole guest list ๐Ÿ’…

@map = map { int( $_/2 } 0..255;
$img->map( red=>\@map );

(and yes, that brace up there is exactly how it's written in the source, no cap โ€” copy it character for character, don't go "fixing" it on me ๐Ÿ™ˆ)


๐Ÿฆ‹ one map to rule them all ๐Ÿฆ‹

You can also specify a single map that gets applied to all channels, alpha channel included. Like, iconic behavior honestly โœจ For example, this applies a gamma correction with a gamma of 1.4 to the input image:

$gamma = 1.4;
@map = map { int( 0.5 + 255*($_/255)**$gamma ) } 0..255;
$img->map(all=> \@map);

The all map is used as a default channel โ€” if no other map is specified for a channel, then the all map is used instead. So it's the fallback bestie, always got your back ๐Ÿซถ

But what if we did not want that gamma touching the alpha channel? (Very valid of us.) Then we would have used:

$img->map(all=> \@map, alpha=>[]);

And here's the trick: since [] contains fewer than 256 element the gamma channel is unaffected. Fewer than 256 = not a full map = not applied. Vibe check passed ๐Ÿ˜Œ


โญ the RGBA order option โญ

It is also possible to simply specify an array of maps that are applied to the images in the RGBA order. For example, to apply maps to the red and blue channels one would use:

$img->map(maps=>[\@redmap, [], \@bluemap]);

Red first, empty slot for green (skipped, living its truth), then blue. Order matters, iykyk ๐ŸŒˆ


โœจ SEE ALSO โœจ

  • Imager
  • Imager::Engines

๐Ÿ’– AUTHOR ๐Ÿ’–

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

๐ŸŽ€ REVISION ๐ŸŽ€

$Revision$


and that's the whole page, bestie!! ๐Ÿฆ‹ you made it to the end, main character energy fr fr ๐Ÿ”ฅ

lil sign-off from the docs themselves: this was rendered by perl v5.42.3, dated 2026-08-19, and the page title is Imager...mations(3pm). Go forth and map those channels, slay ๐Ÿ’…๐Ÿ‘‘
๐Ÿ“ฆ where this page comes from