Imager::Engines(3pm)
๐ธ NAME ๐ธ
Imager::Engines(3pm) โ Programmable transformation operations โจ (yes, from the User Contributed Perl Documentation section, bestie ๐
)
โจ SYNOPSIS โจ
use Imager;
my %opts;
my @imgs;
my $img;
...
my $newimg = $img->transform(
xexpr=>'x',
yexpr=>'y+10*sin((x+y)/10)')
or die $img->errstr;
my $newimg = Imager::transform2(\%opts, @imgs)
or die "transform2 failed: $Imager::ERRSTR";
my $newimg = $img->matrix_transform(
matrix=>[ -1, 0, $img->getwidth-1,
0, 1, 0,
0, 0, 1 ]);
๐ DESCRIPTION ๐
๐ transform()
Okay so transform() is your go-to for making spatial warps, rotations, and that kind of wavy visual sorcery โจ. It only works on one single image, and its whole entire job is to displace pixels. Thatโs it. Thatโs the vibe. ๐
You can feed it operations in postfix notation, or you can use the module Affix::Infix2Postfix to generate postfix code from infix code. Thereโs an example waiting for you in the test case t/t55trans.t ๐.
transform() needs expressions (or opcodes) that determine the source pixel for each target pixel. Source expressions are infix expressions using any of the +, -, *, / or ** binary operators, the - unary operator, ( and ) for grouping, and the sin() and cos() functions. The target pixel is input as the variables x and y. ๐
You specify the x and y expressions as "xexpr" and "yexpr" respectively. You can also specify opcodes directly, but thatโs magic deep enough that you can look at the source code ๐ง.
Note: You can still use thetransform()function, but thetransform2()function is just as fast and is more likely to be enhanced and maintained.
$new_img=$img->transform(xexpr=>'x',yexpr=>'y+10*sin((x+y)/10)')
$new_img=$img->transform(xexpr=>'x+0.1*y+5*sin(y/10.0+1.57)',
yexpr=>'y+10*sin((x+y-0.785)/10)')
๐ฆ transform2()
Imager also supports a transform2() class method, and it lets you do a much more general set of operations than just specifying a spatial transformation like with the transform() method. With transform2() you can also do color transformations, image synthesis, and image combinations from multiple source images. Main character energy, honestly ๐.
transform2() takes a reference to an options hash and a list of images to operate on (this list may be empty):
my %opts;
my @imgs;
...
my $img = Imager::transform2(\%opts, @imgs)
or die "transform2 failed: $Imager::ERRSTR";
The options hash may define a transformation function, and optionally:
widthโ the width of the image in pixels. If this isnโt supplied the width of the first input image is used. If there are no input images an error occurs.heightโ the height of the image in pixels. If this isnโt supplied the height of the first input image is used. If there are no input images an error occurs.constantsโ a reference to hash of constants to define for the expression engine. Some extra constants are defined by Imagerchannelsโ the number of channels in the output image. If this isnโt supplied a 3 channel image will be created.
The transformation function is specified using either the "expr" or "rpnexpr" member of the options โจ.
๐ Infix expressions
You can supply infix expressions to transform 2 with the "expr" keyword.
$opts{expr} = 'return getp1(w-x, h-y)'
The 'expression' supplied follows this general grammar:
( identifier '=' expr ';' )* 'return' expr
This allows you to simplify your expressions using variables ๐.
A more complex example might be:
$opts{expr} = 'pix = getp1(x,y); return if(value(pix)>0.8,pix*0.8,pix)'
Currently to use infix expressions you must have the Parse::RecDescent module installed (available from CPAN). There is also what might be a significant delay the first time you run the infix expression parser due to the compilation of the expression grammar ๐ญ.
๐ฎ Postfix expressions
You can supply postfix or reverse-polish notation expressions to transform2() through the "rpnexpr" keyword.
The parser for "rpnexpr" emulates a stack machine, so operators will expect to see their parameters on top of the stack. A stack machine isnโt actually used during the image transformation itself ๐ซถ.
You can store the value at the top of the stack in a variable called "foo" using !foo and retrieve that value again using @foo. The !foo notation will pop the value from the stack.
An example equivalent to the infix expression above:
$opts{rpnexpr} = 'x y getp1 !pix @pix value 0.8 gt @pix 0.8 * @pix ifp'
At the end of the expression there should be a single pixel value left on the stack, which is used as the output pixel ๐.
๐งฎ Operators
transform2() has a fairly rich range of operators ๐ฅ.
Each entry below includes the usage with "rpnexpr", formatted as:
operand operand ... operator -- result
If the operand or result begins with "N" it is a numeric value, if it begins with "C" it is a color or pixel value.
+, *, -, /, %, ** โ multiplication, addition, subtraction, division, remainder and exponentiation. Multiplication, addition and subtraction can be used on color values too - though you need to be careful - adding 2 white values together and multiplying by 0.5 will give you gray, not white. ๐
Division by zero (or a small number) just results in a large number. Modulo zero (or a small number) results in zero. % is implemented using fmod() so you can use this to take a value mod a floating point value.
"rpnexpr" usage:
N1 N2 + -- N
N1 N2 * -- N
N1 N2 - -- N
N1 N2 / -- N
N1 N2 ** -- N
N1 uminus -- N
sin(N), cos(N), atan2(y,x) โ Some basic trig functions. They work in radians, so you canโt just use the hue values ๐ธ.
"rpnexpr" usage:
N sin -- N
N cos -- N
Ny Nx atan2 -- N
distance(x1, y1, x2, y2) โ Find the distance between two points. This is handy (along with atan2()) for producing circular effects ๐.
"rpnexpr" usage:
Nx1 Ny1 Nx2 Ny2 distance -- N
sqrt(n) โ Find the square root. I havenโt had much use for this since adding the distance() function ๐ซถ.
"rpnexpr" usage:
N sqrt -- N
abs(n) โ Find the absolute value โจ.
"rpnexpr" usage:
N abs -- N
getp1(x,y), getp2(x,y), getp3(x, y) โ Get the pixel at position (x,y) from the first, second or third image respectively. I may add a getpn() function at some point, but this prevents static checking of the instructions against the number of images actually passed in ๐.
"rpnexpr" usage:
Nx Ny getp1 -- C
Nx Ny getp2 -- C
Nx Ny getp3 -- C
value(c), hue(c), sat(c), hsv(h,s,v), hsva(h,s,v,alpha) โ Separates a color value into itโs value (brightness), hue (color) and saturation elements. Use hsv() to put them back together (after suitable manipulation), or hsva() to include a transparency value ๐.
"rpnexpr" usage:
C value -- N
C hue -- N
C sat -- N
Nh Ns Nv hsv -- C
Nh Ns Nv Na hsva -- C
red(c), green(c), blue(c), rgb(r,g,b), rgba(r,g,b,a) โ Separates a color value into itโs red, green and blue colors. Use rgb(r,g,b) to put it back together, or rgba() to include a transparency value ๐.
"rpnexpr" usage:
C red -- N
C green -- N
C blue -- N
Nr Ng Nb rgb -- C
Nr Ng Nb Na rgba -- C
alpha(c) โ Retrieve the alpha value from a color โจ.
"rpnexpr" usage:
C alpha -- N
int(n) โ Convert a value to an integer. Uses a C int cast, so it may break on large values ๐ญ.
"rpnexpr" usage:
N int -- N
if(cond,ntrue,nfalse), if(cond,ctrue,cfalse) โ A simple (and inefficient) if function.
"rpnexpr" usage:
Ncond N-true-result N-false-result if -- N
Ncond C-true-result C-false-result if -- C
Ncond C-true-result C-false-result ifp -- C
<=, <, ==, >=, >, != โ Relational operators (typically used with if()). Since weโre working with floating point values the equalities are โnear equalitiesโ - an epsilon value is used ๐.
N1 N2 <= -- N
N1 N2 < -- N
N1 N2 >= -- N
N1 N2 > -- N
N1 N2 == -- N
N1 N2 != -- N
&&, ||, not(n) โ Basic logical operators ๐ฆ.
"rpnexpr" usage:
N1 N2 and -- N
N1 N2 or -- N
N not -- N
log(n), exp(n) โ Natural logarithm and exponential ๐ฑ.
"rpnexpr" usage:
N log -- N
N exp -- N
det(a, b, c, d) โ Calculate the determinant of the 2 x 2 matrix;
a b
c d
"rpnexpr" usage:
Na Nb Nc Nd det -- N
๐ฎ Constants
transform2() defines the following constants:
piโ The classical constant.w,hโ The width and height of the output image.cx,cyโ The center of the output image.wimage number,himage number โ The width and height of each of the input images,w1is the width of the first input image and so on.cximage number,cyimage number โ The center of each of the input images, (cx1,cy1) is the center of the first input image and so on.
A few examples:
Example 1:
rpnexpr=>'x 25 % 15 * y 35 % 10 * getp1 !pat x y getp1 !pix @pix sat 0.7 gt @pat @pix ifp'
tiles a smaller version of the input image over itself where the color has a saturation over 0.7.
Example 2:
rpnexpr=>'x 25 % 15 * y 35 % 10 * getp1 !pat y 360 / !rat x y getp1 1 @rat - pmult @pat @rat pmult padd'
tiles the input image over itself so that at the top of the image the full-size image is at full strength and at the bottom the tiling is most visible.
Example 3:
rpnexpr=>'x y getp1 !pix @pix value 0.96 gt @pix sat 0.1 lt and 128 128 255 rgb @pix ifp'
replace pixels that are white or almost white with a palish blue.
Example 4:
rpnexpr=>'x 35 % 10 * y 45 % 8 * getp1 !pat x y getp1 !pix @pix sat 0.2 lt @pix value 0.9 gt and @pix @pat @pix value 2 / 0.5 + pmult ifp'
Tiles the input image over it self where the image isnโt white or almost white.
Example 5:
rpnexpr=>'x y 160 180 distance !d y 180 - x 160 - atan2 !a @d 10 / @a + 3.1416 2 * % !a2 @a2 180 * 3.1416 / 1 @a2 sin 1 + 2 / hsv'
Produces a spiral ๐.
Example 6:
rpnexpr=>'x y 160 180 distance !d y 180 - x 160 - atan2 !a @d 10 / @a + 3.1416 2 * % !a2 @a 180 * 3.1416 / 1 @a2 sin 1 + 2 / hsv'
A spiral built on top of a color wheel ๐.
Lowkey the most unhinged part of this whole thing is that you can justโฆ describe a picture in math and Perl will hand it to you. Anyway, bestie, here's the rest:
For all the juicy details on how expressions get parsed, go peek at Imager::Expr. And if you're the type who needs to know what the virtual machine is doing under the hood while it transforms your images โ that's Imager::regmach, babes. ๐ง
# generate a colorful spiral
# requires that Parse::RecDescent be installed
my $newimg = Imager::transform2({
width => 160, height=>160,
expr => <<EOS
dist = distance(x, y, w/2, h/2);
angle = atan2(y-h/2, x-w/2);
angle2 = (dist / 10 + angle) % ( 2 * pi );
return hsv(angle*180/pi, 1, (sin(angle2)+1)/2);
EOS
});
Like, hello?? That's a whole colorful spiral?? From six lines of vibes?? ๐ญโจ
# replace green portions of an image with another image
my $newimg = Imager::transform2({
rpnexpr => <<EOS
x y getp2 !pat # used to replace green portions
x y getp1 !pix # source with "green screen"
@pix red 10 lt @pix blue 10 lt && # low blue and red
@pix green 254 gt && # and high green
@pat @pix ifp
EOS
}, $source, $background);
Green-screen energy, but make it RPN. ๐ The comments in there are doing the absolute most to explain themselves, and honestly? Iconic behavior.
๐ Matrix Transformations ๐
matrix_transform() ๐
So writing code in a whole little language not your thing? Fair. You can skip the language entirely and use a matrix to do affine transformations instead, via the matrix_transform() method:
my $newimg = $img->matrix_transform(matrix=>[ -1, 0, $img->getwidth-1,
0, 1, 0,
0, 0, 1 ]);
By default the output image comes out the same size as the input image โ cute, predictable. But you can pass the xsize and ysize parameters if you want to change the size. ๐
And ngl, building matrices by hand is giving homework, so you don't have to โ the Imager::Matrix2d module will build them for you. That class has methods that let you scale, shear, rotate, translate and reflect, and you can combine them all with an overloaded multiplication operator. Slay. โจ
WARNING: the matrix you hand over in the matrix operator transforms the co-ordinates within the destination image to the co-ordinates within the source image. Yes, that direction. Yes, it's backwards from what your brain wants. It can be confusing โ no cap, fr fr. ๐
You can also pass a "back" argument, which acts as a background color for the areas of the image where there are no samples available (i.e. outside the rectangle of the source image). It can be either an Imager::Color or an Imager::Color::Float object. And heads up bestie: this is not mixed into 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. Different situation, different vibe. ๐
๐ AUTHOR ๐
Tony Cook <tonyc@cpan.org>, Arnar M. Hrafnkelsson
That's the whole page, babe โ you made it to the end ๐ซถ This little masterpiece is perl v5.42.3, dated 2026-08-19, and it's Imager::Engines(3pm) from the User Contributed Perl Documentation. Go forth and transform some images, you absolute main character. ๐๐ธ
๐ฆ where this page comes from
- ubuntu stonking: libimager-perl 1.035+dfsg-1 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms