Imager::Draw(3pm)

πŸ’– Imager::Draw(3pm) πŸ’–

okay bestie, welcome to the Imager::Draw(3pm) page from the User Contributed Perl Documentation. It is literally all about drawing primitives onto images, and the vibe is immaculate. ✨

🌸 NAME 🌸

Imager::Draw β€” Draw primitives to images πŸ’…

✨ SYNOPSIS ✨

bestie, here's the whole little code mood board:

  use Imager;
  use Imager::Fill;

  $img = ...;
  $blue = Imager::Color->new( 0, 0, 255 );
  $fill = Imager::Fill->new(hatch=>'stipple');

  $img->line(color=>$blue, x1=>10, x2=>100,
                             y1=>20, y2=>50, aa=>1, endp=>1 );

  $img->polyline(points=>[[$x0,$y0], [$x1,$y1], [$x2,$y2]],
                 color=>$blue);
  $img->polyline(x=>[$x0,$x1,$x2], y=>[$y0,$y1,$y2], aa=>1);

  $img->box(color=> $blue, xmin=> 10, ymin=>30,
                             xmax=>200, ymax=>300, filled=>1);
  $img->box(fill=>$fill);

  $img->arc(color=>$blue, r=>20, x=>200, y=>100,
            d1=>10, d2=>20 );

  $img->circle(color=>$blue, r=>50, x=>200, y=>100);

  $img->polygon(points=>[[$x0,$y0], [$x1,$y1], [$x2,$y2]],
                color=>$blue);

  $img->polygon(x=>[$x0,$x1,$x2], y=>[$y0,$y1,$y2]);

  $img->flood_fill(x=>50, y=>50, color=>$color);

  $img->setpixel(x=>50, y=>70, color=>$color);

  $img->setpixel(x=>[ 50, 60, 70 ], y=>[20, 30, 40], color=>$color);

  my $color = $img->getpixel(x=>50, y=>70);

  my @colors = $img->getpixel(x=>[ 50, 60, 70 ], y=>[20, 30, 40]);

  # drawing text
  my $font = Imager::Font->new(...) or die;
  $img->string(x => 50, y => 70,
               font => $font,
               string => "Hello, World!",
               color => 'red',
               size => 30,
               aa => 1);

  # bottom right-hand corner of the image
  $img->align_string(x => $img->getwidth() - 1,
                     y => $img->getheight() - 1,
                     halign => 'right',
                     valign => 'bottom',
                     string => 'Imager',
                     font => $font,
                     size => 12);

  # low-level functions
  my @colors = $img->getscanline(y=>50, x=>10, width=>20);

  $img->setscanline(y=>60, x=>20, pixels=>\@colors);

  my @samples = $img->getsamples(y=>50, x=>10, width=>20,
                                 channels=>[ 2, 0 ]);

πŸ’œ DESCRIPTION πŸ’œ

It is possible to draw with graphics primitives onto images. Such primitives include boxes, arcs, circles, polygons and lines. The coordinate system in Imager has the origin (0,0) in the upper left corner of an image with co-ordinates increasing to the right and bottom. For non anti-aliasing operation all coordinates are rounded towards the nearest integer. For anti-aliased operations floating point coordinates are used.

Drawing is assumed to take place in a coordinate system of infinite resolution. This is the typical convention and really only matters when it is necessary to check for off-by-one cases. Typically it's useful to think of (10, 20) as (10.00, 20.00) and consider the consequences. 🫢

🌈 Color Parameters 🌈

The "color" parameter for any of the drawing methods can be an Imager::Color object, a simple scalar that Imager::Color can understand, a hashref of parameters that Imager::Color->new understands, or an arrayref of red, green, blue values, for example:

  $image->box(..., color=>'red');
  $image->line(..., color=>'#FF0000');
  $image->flood_fill(..., color=>[ 255, 0, 255 ]);

While supplying colors as names, array references or CSS color specifiers is convenient, for maximum performance you should supply the color as an Imager::Color object:

  my @colors = map Imager::Color->new($_), qw/red green blue/
  for my $i (1..1000) {
    $image->box(..., color => $colors[rand @colors]);
  }

πŸ“ Fill Parameters πŸ“

All filled primitives, i.e. arc(), box(), circle(), polygon() and the flood_fill() method can take a "fill" parameter instead of a "color" parameter which can either be an Imager::Fill object, or a reference to a hash containing the parameters used to create the fill, for example:

  $image->box(..., fill=>{ hatch => 'check1x1' });
  my $fillimage = Imager->new;
  $fillimage->read(file=>$somefile) or die;
  $image->flood_fill(..., fill=>{ image=>$fillimage });

Currently you can create opaque or transparent plain color fills, hatched fills, image based fills and fountain fills. See Imager::Fill for more information. πŸŽ€

πŸ”₯ Polygon Fill Modes πŸ”₯

When filling a polygon that overlaps itself, or when filling several polygons with polypolygon() that overlap each other, you can supply a "mode" parameter that controls how the overlap is resolved. This can have one of two possible values:

  • "evenodd" β€” if areas overlap an odd number of times, they are filled, and are otherwise unfilled. This is the default and the historical Imager polygon fill mode.
  • "nonzero" β€” areas that have an unbalanced clockwise and anti-clockwise boundary are filled. This is the same as "WindingRule" for X and "WINDING" for Win32 GDI.

"nonzero" allows polygons to overlap, either with itself, or with another polygon in the same polypolygon() call, without producing unfilled area in the overlap, and also allows areas to be cut out of the area by specifying the points making up a cut-out in the opposite order. πŸ’€

🧚 List of primitives 🧚

✨ line() ✨

  $img->line(color=>$green, x1=>10, x2=>100,
                                      y1=>20, y2=>50, aa=>1, endp=>1 );

Draws a line from (x1,y1) to (x2,y2). The endpoint (x2,y2) is drawn by default. If "endp" of 0 is specified then the endpoint will not be drawn. If "aa" is set then the line will be drawn anti-aliased. The "antialias" parameter is still available for backwards compatibility.

Parameters:

  • "x1", "y1" β€” starting point of the line. Required.
  • "x2", "y2" β€” end point of the line. Required.
  • "color" β€” the color of the line. See "Color Parameters". Default: black.
  • "endp" β€” if zero the end point of the line is not drawn. Default: 1 - the end point is drawn. This is useful to set to 0 when drawing a series of connected lines.
  • "aa" β€” if true the line is drawn anti-aliased. Default: 0.

🌸 polyline() 🌸

  $img->polyline(points=>[[$x0,$y0],[$x1,$y1],[$x2,$y2]],color=>$red);
  $img->polyline(x=>[$x0,$x1,$x2], y=>[$y0,$y1,$y2], aa=>1);

"polyline" is used to draw multiple lines between a series of points. The point set can either be specified as an arrayref to an array of array references (where each such array represents a point). The other way is to specify two array references.

The "antialias" parameter is still available for backwards compatibility. πŸ¦‹

  • points β€” a reference to an array of references to arrays containing the co-ordinates of the points in the line, for example:
  my @points = ( [ 0, 0 ], [ 100, 0 ], [ 100, 100 ], [ 0, 100 ] );
  $img->polyline(points => \@points);
  • x, y β€” each is an array of x or y ordinates. This is an alternative to supplying the "points" parameter.
  # same as the above points example
  my @x = ( 0, 100, 100, 0 );
  my @y = ( 0, 0, 100, 100 );
  $img->polyline(x => \@x, y => \@y);
  • "color" β€” the color of the line. See "Color Parameters". Default: black.
  • "aa" β€” if true the line is drawn anti-aliased. Default: 0. Can also be supplied as "antialias" for backward compatibility.

πŸŽ€ box() πŸŽ€

  $blue = Imager::Color->new( 0, 0, 255 );
  $img->box(color => $blue, xmin=>10, ymin=>30, xmax=>200, ymax=>300,
            filled=>1);

If any of the edges of the box are omitted it will snap to the outer edge of the image in that direction. If "filled" is omitted the box is drawn as an outline. Instead of a color it is possible to use a "fill" pattern:

  $fill = Imager::Fill->new(hatch=>'stipple');
  $img->box(fill=>$fill);  # fill entire image with a given fill pattern

  $img->box(xmin=>10, ymin=>30, xmax=>150, ymax=>60,
            fill => { hatch=>'cross2' });

Also if a color is omitted a color with (255,255,255,255) is used instead. [NOTE: This may change to use $img->fgcolor() in the future].

Box does not support fractional coordinates yet. 😭

Parameters:

  • "xmin" β€” left side of the box. Default: 0 (left edge of the image)
  • "ymin" β€” top side of the box. Default: 0 (top edge of the image)
  • "xmax" β€” right side of the box. Default: $img->getwidth-1. (right edge of the image)
  • "ymax" β€” bottom side of the box. Default: $img->getheight-1. (bottom edge of the image)

Note: "xmax" and "ymax" are inclusive - the number of pixels drawn for a filled box is (xmax-xmin+1) * (ymax-ymin+1).

  • "box" β€” a reference to an array of (left, top, right, bottom) co-ordinates. This is an alternative to supplying "xmin", "ymin", "xmax", "ymax" and overrides their values.
  • "color" β€” the color of the line. See "Color Parameters". Default: white. This is ignored if the filled parameter
  • "filled" β€” if non-zero the box is filled with color instead of outlined. Default: an outline is drawn.
  • "fill" β€” the fill for the box. If this is supplied then the box will be filled. See "Fill Parameters".

πŸ”₯ arc() πŸ”₯

  $img->arc(color=>$red, r=>20, x=>200, y=>100, d1=>10, d2=>20 );

This creates a filled red arc with a 'center' at (200, 100) and spans 10 degrees and the slice has a radius of 20.

It's also possible to supply a "fill" parameter.

To draw just an arc outline - just the curve, not the radius lines, set filled to 0:

Parameters:

  $img->arc(color=>$red, r=>20, x=>200, y=>100, d1=>10, d2=>20, filled=>0 );
  • "x", "y" β€” center of the filled arc. Default: center of the image.
  • "r" β€” radius of the arc. Default: 1/3 of min(image height, image width).
  • "d1" β€” starting angle of the arc, in degrees. Default: 0
  • "d2" β€” ending angle of the arc, in degrees. Default: 361.
  • "color" β€” the color of the filled arc. See "Color Parameters". Default: white. Overridden by "fill".
  • "fill" β€” the fill for the filled arc. See "Fill Parameters"
  • "aa" β€” if true the filled arc is drawn anti-aliased. Default: false.

Anti-aliased arc() is experimental for now, I'm not entirely happy with the results in some cases.

  • "filled" β€” set to 0 to draw only an outline.
  # arc going through angle zero:
  $img->arc(d1=>320, d2=>40, x=>100, y=>100, r=>50, color=>'blue');

okay more arc() inspo, because the vibes deserve options πŸ’…:

# complex fill arc
$img->arc(d1=>135, d2=>45, x=>100, y=>150, r=>50,
          fill=>{ solid=>'red', combine=>'diff' });

# draw an anti-aliased circle outline
$img->arc(x => 100, y => 150, r => 150, filled => 0,
          color => '#F00', aa => 1);

# draw an anti-aliased arc
$img->arc(x => 100, y => 150, r => 90, filled => 0,
          color => '#0f0', aa => 1, d1 => 90, d2 => 180);

πŸŽ€ circle()

$img->circle(color=>$green, r=>50, x=>200, y=>100, aa=>1, filled=>1);

This one serves an anti-aliased green circle, center parked at (200, 100), radius 50. Iconic. And bestie, you can also slide a fill parameter in there instead of color:

$img->circle(r => 50, x=> 150, y => 150, fill=>{ hatch => 'stipple' });

Want just the outline, no filled-in moment? Set filled to 0:

$img->circle(color=>$green, r=>50, x=>200, y=>100, aa=>1, filled=>0);
  • x, y β€” center of the filled circle. Default: center of the image.
  • r β€” radius of the circle. Default: 1/3 of min(image height, image width).
  • color β€” the color of the filled circle. See "Color Parameters". Default: white. Overridden by fill.
  • fill β€” the fill for the filled circle. See "Fill Parameters".
  • aa β€” if true the filled circle is drawn anti-aliased. Default: false.
  • filled β€” set to 0 to just draw an outline.

🌈 polygon()

$img->polygon(points=>[[$x0,$y0],[$x1,$y1],[$x2,$y2]],color=>$red);
$img->polygon(x=>[$x0,$x1,$x2], y=>[$y0,$y1,$y2], fill=>$fill);

Polygon is the one that draws a filled polygon. Heads up tho: currently the polygon is always drawn anti-aliased, although that will change in the future. Like other anti-aliased drawing functions its coordinates can be specified with floating point values πŸ¦‹. And as with other filled shapes it's possible to use a fill instead of a color.

  • points β€” a reference to an array of references to arrays containing the co-ordinates of the points in the line, for example:
my @points = ( [ 0, 0 ], [ 100, 0 ], [ 100, 100 ], [ 0, 100 ] );
$img->polygon(points => \@points);
  • x, y β€” each is an array of x or y ordinates. This is an alternative to supplying the points parameter.
# same as the above points example
my @x = ( 0, 100, 100, 0 );
my @y = ( 0, 0, 100, 100 );
$img->polygon(x => \@x, y => \@y);
  • color β€” the color of the filled polygon. See "Color Parameters". Default: black. Overridden by fill.
  • fill β€” the fill for the filled circle. See "Fill Parameters".
  • mode β€” fill mode for the polygon. See "Polygon Fill Modes".
⚠️ Note: the points specified are as offsets from the top-left of the image, not as pixel locations. Which means this:
$img->polygon(points => [ [ 0, 0 ], [ 1, 0 ], [ 1, 1 ], [ 0, 1 ] ]);

fills only a single pixel at (0, 0), not four. literally one pixel. that's it. πŸ™ˆ


πŸ¦‹ polypolygon()

$img->polypolygon(points => $points, color => $color);

Draw multiple polygons, either filled or unfilled β€” it's giving multitasking main character energy πŸ‘‘

  • points β€” is an array reference containing polygon definitions, each polygon definition is a reference to an array containing two arrays, one each for the x and y co-ordinates.
  • filled β€” if true, fill the polygons with the color defined by color.
  • color β€” the color to draw the polygons with if fill is not supplied.
  • fill β€” fill the polygons with this fill if supplied.
  • mode β€” fill mode for the polygon. See "Polygon Fill Modes".
⚠️ Note: the points specified are as offsets from the top-left of the image, not as pixel locations. This means that:
$img->polypolygon(points => [ [ [ 0, 1, 1, 0 ], [ 0, 0, 1, 1 ] ] ],
                  filled => 1);

fills only a single pixel at (0, 0), not four. yes bestie, same rule as before, no cap πŸ’€


πŸ’§ flood_fill()

You can fill a region that all has the same color using the flood_fill() method, for example:

$img->flood_fill(x=>50, y=>50, color=>$color);

will fill all regions the same color connected to the point (50, 50).

Alternatively you can fill a region limited by a given border color:

# stop at the red border
$im->flood_fill(x=>50, y=>50, color=>$color, border=>"red");

You can also fill with a complex fill:

$img->flood_fill(x=>50, y=>50, fill=>{ hatch=>'cross1x1' });

Parameters:

  • x, y β€” the start point of the fill.
  • color β€” the color of the filled area. See "Color Parameters". Default: white. Overridden by fill.
  • fill β€” the fill for the filled area. See "Fill Parameters".
  • border β€” the border color of the region to be filled. If this parameter is supplied flood_fill() will stop when it finds this color. If this is not supplied then a normal fill is done. border can be supplied as a "Color Parameters".

πŸ“ setpixel()

$img->setpixel(x=>50, y=>70, color=>$color);
$img->setpixel(x=>[ 50, 60, 70 ], y=>[20, 30, 40], color=>$color);

setpixel() is used to set one or more individual pixels. tiny little pixel glow-ups ✨

You can supply a single set of co-ordinates as scalar x and y parameters, or set either to an arrayref of ordinates.

If one array is shorter than another the final value in the shorter will be duplicated until they match in length.

If only one of x or y is an array reference then setpixel() will behave as if the non-reference value were an array reference containing only that value.

eg.

my $count = $img->setpixel(x => 1, y => [ 0 .. 3 ], color => $color);

behaves like:

my $count = $img->setpixel(x => [ 1 ], y => [ 0 .. 3 ], color => $color);

and since the final element in the shorter array is duplicated, this behaves like:

my $count = $img->setpixel(x => [ 1, 1, 1, 1 ], y => [ 0 .. 3 ],
                           color => $color);

To set an entire or partial row of pixels in one call, consider the "setscanline()" in Imager::Draw or "setsamples()" in Imager::Draw methods.

Parameters:

  • x, y β€” either integers giving the co-ordinates of the pixel to set or array references containing a set of pixels to be set.
  • color β€” the color of the pixels drawn. See "Color Parameters". Default: white.

Returns the number of pixels drawn, if no pixels were drawn, but none of the errors below occur, returns "0 but true".

For other errors, setpixel() returns an empty list and sets errstr().

Possible errors conditions include:

  • the image supplied is empty
  • a reference to an empty array was supplied for x or y
  • x or y wasn't supplied
  • color isn't a valid color, and can't be converted to a color.

πŸ‘€ getpixel()

my $color = $img->getpixel(x=>50, y=>70);
my @colors = $img->getpixel(x=>[ 50, 60, 70 ], y=>[20, 30, 40]);
my $colors_ref = $img->getpixel(x=>[ 50, 60, 70 ], y=>[20, 30, 40]);

getpixel() is used to retrieve one or more individual pixels. the reading girlies get it πŸ’…

You can supply a single set of co-ordinates as scalar x and y parameters, or set each to an arrayref of ordinates.

If one array is shorter than another the final value in the shorter will be duplicated until they match in length.

If only one of x or y is an array reference then getpixel() will behave as if the non-reference value were an array reference containing only that value.

eg.

my @colors = $img->getpixel(x => 0, y => [ 0 .. 3 ]);

behaves like:

my @colors = $img->getpixel(x => [ 0 ], y => [ 0 .. 3 ]);

and since the final element in the shorter array is duplicated, this behaves like:

my @colors = $img->getpixel(x => [ 0, 0, 0, 0 ], y => [ 0 .. 3 ]);

To receive floating point colors from getpixel(), set the type parameter to 'float'.

To retrieve an entire or partial row of pixels, or pixel data, in one call, consider the "getscanline()" in Imager::Draw or "getsamples()" in Imager::Draw methods.

Parameters:

  • x, y β€” either integers giving the co-ordinates of the pixel to set or array references containing a set of pixels to be set.
  • type β€” the type of color object to return, either '8bit' for Imager::Color objects or 'float' for Imager::Color::Float objects. Default: '8bit'.

When called with an array reference for either or x or y, getpixel() will return a list of colors in list context, and an arrayref in scalar context.

If a supplied co-ordinate is outside the image then undef is returned for the pixel.

Each color is returned as an Imager::Color object or as an Imager::Color::Float object if type is set to float.

Possible errors conditions include:

  • the image supplied is empty
  • a reference to an empty array was supplied for x or y
  • x or y wasn't supplied
  • type isn't a valid value.

For any of these errors getpixel() returns an empty list.


✨ string()

my $font = Imager::Font->new(file=>"foo.ttf");
$img->string(x => 50, y => 70,
             string => "Hello, World!",
             font => $font,
             size => 30,
             aa => 1,
             color => 'white');

Draws text on the image. the moment where your pic becomes a whole aesthetic 🫢

Parameters:

  • x, y β€” the point to draw the text from. If align is 0 this is the top left of the string. If align is 1 (the default) then this is the left of the string on the baseline. Required.
  • string β€” the text to draw. Required unless you supply the text parameter.
  • font β€” an Imager::Font object representing the font to draw the text with. Required.
  • aa β€” if non-zero the output will be anti-aliased. Default: the value set in Imager::Font->new() or 0 if not set.
  • align β€” if non-zero the point supplied in (x,y) will be on the base-line, if zero then (x,y) will be at the top-left of the string.

i.e. if drawing the string "yA" and align is 0 the point (x,y) will aligned with the top of the A. If align is 1 (the default) it will be aligned with the baseline of the font, typically bottom of the A, depending on the font used.

The default for that one: whatever you set in Imager::Font->new, or 1 if you never set anything. Slay.

  • channel β€” if you pass this, your text gets written into that specific channel of the image and the color parameter gets straight-up ignored. Lowkey rude to color, but okay.
  • color β€” the color your text is drawn in. Default: whatever color you handed to Imager::Font->new, or red if you gave it nothing.
  • size β€” the point size to draw the text at. Default: the size from Imager::Font->new, or 15.
  • sizew β€” the width scaling to draw the text at. Default: whatever size is.
  • utf8 β€” for drivers that support it, treat the string as UTF-8 encoded. On perl versions with Unicode support (5.6 and later) this turns on automatically when the string parameter is already a UTF-8 string. Peep "UTF-8" in Imager::Font for the whole story.
  • vlayout β€” for drivers that support it, draw the text vertically. Note from the author, and I quote the vibe: I haven't found a font that has the appropriate metrics yet. 😭 so like. good luck bestie.
  • text β€” alias for the string parameter. Same thing, different name, we love an understudy. πŸŽ€

If something goes wrong, string() returns false and you hit up $img->errstr to find out why. No mystery, no guessing, we investigate. πŸ”


πŸ¦‹ align_string() πŸ¦‹

Draws text all aligned and cute around a point on the image. Basically string() but with main character positioning energy.

# "Hello" centered at 100, 100 in the image.
my ($left, $top, $right, $bottom) =
  $img->align_string(string=>"Hello",
                     x=>100, y=>100,
                     halign=>'center', valign=>'center',
                     font=>$font);

Parameters, let's go:

  • x, y β€” the point to draw the text from. If align is 0 this is the top left of the string. If align is 1 (the default) then this is the left of the string on the baseline. Required. No point, no text, periodt.
  • string β€” the text to draw. Required unless you supply the text parameter instead.
  • font β€” an Imager::Font object representing the font to draw the text with. Required. Yes bestie you actually need a font, that's kind of the whole thing.
  • aa β€” if it's non-zero the output will be anti-aliased. ✨
  • valign β€” vertical alignment of the text against (x,y):
    • top β€” Point is at the top of the text.
    • bottom β€” Point is at the bottom of the text.
    • baseline β€” Point is on the baseline of the text. This is the default.
    • center β€” Point is vertically centered within the text.
  • halign β€” horizontal alignment of the text against (x,y):
    • left β€” The point is at the left of the text. This is the default.
    • start β€” The point is at the start point of the text.
    • center β€” The point is horizontally centered within the text.
    • right β€” The point is at the right end of the text.
    • end β€” The point is at the end point of the text.
  • channel β€” same deal as before: if present, the text is written to that specified channel of the image and the color parameter is ignored.
  • color β€” the color to draw the text in. Default: the color supplied to Imager::Font->new, or red if none.
  • size β€” the point size to draw the text at. Default: the size supplied to Imager::Font->new, or 15.
  • sizew β€” the width scaling to draw the text at. Default: the value of size.
  • utf8 β€” for drivers that support it, treat the string as UTF-8 encoded. For perl versions that support Unicode (5.6 and later) this gets enabled automatically if the string parameter is already a UTF-8 string. See "UTF-8" in Imager::Font for more info.
  • vlayout β€” for drivers that support it, draw the text vertically. (Again: I haven't found a font that has the appropriate metrics yet. πŸ™ˆ)
  • text β€” alias for the string parameter.

When it works, you get back a list of the bounds of the drawn text, in the order left, top, right, bottom. Very demure, very mindful, very useful. πŸ’…

When it doesn't work, align_string() returns an empty list and you can use "$img->errstr" to get the reason for the error.


🌈 setscanline() 🌈

Sets all or part of a horizontal line of pixels on an image. Honestly this method is at its best when you pair it with getscanline() β€” they're a matching set, iykyk. πŸ’–

The parameters you can pass:

  • y β€” vertical position of the scan line. Required. Can't skip this one.
  • x β€” position to start on the scan line. Default: 0
  • pixels β€” either a reference to an array containing Imager::Color objects, a reference to an array containing Imager::Color::Float objects, or a scalar containing packed color data.

If type is index then this can either be a reference to an array of palette color indexes or a scalar containing packed indexes.

Check out "Packed Color Data" for the scoop on the format of packed color data.

  • type β€” the type of pixel data you're supplying. If you hand over an array reference then this gets figured out automatically. If you supply packed color data it defaults to '8bit', and if your data is packed floating point color data then you need to set this to 'float'.

You can use float or 8bit samples with any image.

If this is index then pixels should be either an array of palette color indexes or a packed string of color indexes.

Returns the number of pixels set. Numbers! πŸ“Š

Each one of these next examples sets 5 pixels from (5, 10) through (9, 10) to blue, red, blue, red, blue:

my $red_color = Imager::Color->new(255, 0, 0);
my $blue_color = Imager::Color->new(0, 0, 255);

$image->setscanline(y=>10, x=>5, pixels=>
                    [ ($blue_color, $red_color) x 2, $blue_color ]);

# use floating point color instead, for 16-bit plus images
my $red_colorf = Imager::Color::Float->new(1.0, 0, 0);
my $blue_colorf = Imager::Color::Float->new(0, 0, 1.0);

$image->setscanline(y=>10, x=>5, pixels=>
                    [ ($blue_colorf, $red_colorf) x 2, $blue_colorf ]);

# packed 8-bit data
$image->setscanline(y=>10, x=>5, pixels=>
                    pack("C*", ((0, 0, 255, 255), (255, 0, 0, 255)) x 2,
                          (0, 0, 255, 255)));

# packed floating point samples
$image->setscanline(y=>10, x=>5, type=>'float', pixels=>
                    pack("d*", ((0, 0, 1.0, 1.0), (1.0, 0, 0, 1.0)) x 2,
                          (0, 0, 1.0, 1.0)));

Copy even rows from one image to another β€” a little copy-paste situation but make it pixels:

for (my $y = 0; $y < $im2->getheight; $y+=2) {
  $im1->setscanline(y=>$y,
                    pixels=>scalar($im2->getscanline(y=>$y)));
}

Set the blue channel to 0 for all pixels in an image. This could be done with convert too, but look at us, doing it manually:

for my $y (0..$im->getheight-1) {
  my $row = $im->getscanline(y=>$y);
  $row =~ s/(..).(.)/$1\0$2/gs;
  $im->setscanline(y=>$y, pixels=>$row);
}

πŸ’œ getscanline() πŸ’œ

Reads all or part of a horizontal line of pixels from an image. Bestie to setscanline(), obviously β€” the matching-set energy is real. 🫢

The parameters you can pass:

  • y β€” vertical position of the scan line. Required.
  • x β€” position to start on the scan line. Default: 0
  • width β€” number of pixels to read. Default: $img->getwidth - x
  • type β€” the type of pixel data to return. Default: "8bit".

Permitted values are "8bit" and "float" and "index".

In list context this method returns a list of Imager::Color objects when type is "8bit", or a list of Imager::Color::Float objects when type is "float", or a list of integers when type is "index".

In scalar context this returns packed 8-bit pixels when type is "8bit", or a list of packed floating point pixels when type is "float", or packed palette color indexes when type is "index".

Big caveat bestie: the values of samples for which the image does not have channels is undefined. So for a single channel image, the values of channels 1 through 3 are undefined. Not a vibe, just how it is. πŸ’€

Check the image for a given color β€” a lil' find-the-needle situation:

my $found;
YLOOP: for my $y (0..$img->getheight-1) {
  my @colors = $img->getscanline(y=>$y);
  for my $color (@colors) {
    my ($red, $green, $blue, $alpha) = $color->rgba;
    if ($red == $test_red && $green == $test_green && $blue == $test_blue
        && $alpha == $test_alpha) {
      ++$found;
      last YLOOP;
    }
  }
}

Or do the whole thing with packed data, because we're efficient like that:

my $found;
my $test_packed = pack("CCCC", $test_red, $test_green, $test_blue,
                       $test_alpha);
YLOOP: for my $y (0..$img->getheight-1) {
  my $colors = $img->getscanline(y=>$y);
  while (length $colors) {
    if (substr($colors, 0, 4, '') eq $test_packed) {
      ++$found;
      last YLOOP;
    }
  }
}

There are more examples hanging out in setscanline() if you want more β€” go peek. ✨


πŸŽ€ getsamples() πŸŽ€

Reads specified channels from all or part of a horizontal line of pixels from an image. So like getscanline() but you get to pick exactly which channels you want. Choose your own adventure, honestly. πŸ¦‹

The parameters you can pass:

  • y β€” vertical position of the scan line. Required.
  • x β€” position to start on the scan line. Default: 0
  • width β€” number of pixels to read. Default: "$img->getwidth - x"
  • type β€” the type of sample data to return. Default: "8bit".

Permitted values are "8bit" and "float".

As of Imager 0.61 this can be "16bit" β€” but only for 16 bit images.

  • channels β€” a reference to an array of channels to return, where 0 is the first channel. Default: "[ 0 .. $self->getchannels()-1 ]"
  • target β€” if you supply an array reference here, the samples get stored into it instead of being returned to you. Very "I'll bring my own container" of you.
  • offset β€” the offset within the array referenced by target. (For the target people.)

In list context this returns a list of integers between 0 and 255 inclusive when type is "8bit", or a list of floating point numbers between 0.0 and 1.0 inclusive when type is "float". πŸ“

In scalar context this returns a string of packed bytes, exactly as with pack("C*", ...) when type is "8bit", or a string of packed doubles as with pack("d*", ...) when type is "float".

If the target option is supplied then only a count of samples is returned πŸ’…

Example: check if any pixels in an image have a non-zero alpha channel β€” bestie this is how you vibe-check transparency:

my $has_coverage;
for my $y (0 .. $img->getheight()-1) {
  my $alpha = $img->getsamples(y=>$y, channels=>[0]);
  if ($alpha =~ /[^\0]/) {
    ++$has_coverage;
    last;
  }
}

Example: convert a 2 channel gray image into a 4 channel RGBA image β€” no cap, the comments said it:

# this could be done with convert() instead
my $out = Imager->new(xsize => $src->getwidth(),
                      ysize => $src->getheight(),
                      channels => 4);
for my $y ( 0 .. $src->getheight()-1 ) {
  my $data = $src->getsamples(y=>$y, channels=>[ 0, 0, 0, 1 ]);
  $out->setscanline(y=>$y, pixels=>$data);
}

Retrieve 16-bit samples β€” the way this only works when $img->bits == 16 is so specific:

if ($img->bits == 16) {
  my @samples;
  $img->getsamples(x => 0, y => $y, target => \@samples, type => '16bit');
}

🫢 setsamples() β€” writing samples like a main character

This one lets you write samples to an image. Parameters, bestie:

  • "y" β€” vertical position of the scan line. This parameter is required. Like, mandatory mandatory.
  • "x" β€” position to start on the scan line. Default: 0.
  • "width" β€” number of pixels to write. Default: "$img->getwidth - x". The minimum of this and the number of pixels represented by the samples provided will be written.
  • "type" β€” the type of sample data to write. This parameter is required. This can be "8bit", "float" or for 16-bit images only, "16bit".
  • "channels" β€” a reference to an array of channels to return, where 0 is the first channel. Default: "[ 0 .. $self->getchannels()-1 ]".
  • "data" β€” for a type of "8bit" or "float" this can be a reference to an array of samples or a scalar containing packed samples. If "data" is a scalar it may only contain characters from \x00 to \xFF. For a type of "16bit" this can only be a reference to an array of samples to write. Required.
  • "offset" β€” the starting offset within the array referenced by data. If "data" is a scalar containing packed samples this offset is in samples.

Returns the number of samples written. Slay.

$targ->setsamples(y => $y, data => \@data);

$targ->setsamples(y => $y, data => \@data, offset => $src->getchannels);

Copy from one image to another β€” literally the blueprint:

my $targ = Imager->new(xsize => $src->getwidth,
      ysize => $src->getheight, channels => $src->getchannels);
for my $y (0 .. $targ->getheight()-1) {
  my $row = $src->getsamples(y => $y)
    or die $src->errstr;
  $targ->setsamples(y => $y, data => $row)
    or die $targ->errstr;;
}

Compose an image from separate source channels β€” this is giving collage energy:

my @src = ...; # images to work from, up to 4
my $targ = Imager->new(xsize => $src[0]->getwidth,
   ysize => $src[0]->getheight, channels => scalar(@src));
for my $y (0 .. $targ->getheight()-1) {
  for my $ch (0 .. $#src) {
    my $row = $src[$ch]->getsamples(y => $y, channels => [ 0 ]);
    $targ->setsamples(y => $y, data => $row, channels => [ $ch ] );
  }
}

🌈 Packed Color Data β€” performance girlie behavior

The getscanline() and setscanline() methods can work with pixels packed into scalars. This is useful to remove the cost of creating color objects, but should only be used when performance is an issue. Like, don't do this for funsies.

The getsamples() and setsamples() methods can work with samples packed into scalars.

Packed data can either be 1 byte per sample or 1 double per sample.

Each pixel returned by getscanline() or supplied to setscanline() contains 4 samples, even if the image has fewer than 4 channels. The values of the extra samples as returned by getscanline() is not specified. The extra samples passed to setscanline() are ignored.

To produce packed 1 byte/sample pixels, use the pack "C" template:

my $packed_8bit_pixel = pack("CCCC", $red, $blue, $green, $alpha);

To produce packed double/sample pixels, use the pack "d" template:

my $packed_float_pixel = pack("dddd", $red, $blue, $green, $alpha);

Note that double/sample data is always stored using the C "double" type, never "long double", even if "perl" is built with "-Duselongdouble". Periodt.

If you use a type parameter of "index" then the values are palette color indexes, not sample values:

my $im = Imager->new(xsize => 100, ysize => 100, type => 'paletted');
my $black_index = $im->addcolors(colors => [ 'black' ]);
my $red_index = $im->addcolors(colors => [ 'red' ]);
# 2 pixels
my $packed_index_data = pack("C*", $black_index, $red_index);
$im->setscanline(y => $y, pixels => $packed_index_data, type => 'index');

πŸ¦‹ Combine Types β€” the mix-and-match menu

Some methods accept a "combine" parameter, this can be any of the following:

  • "none" β€” the fill pixel replaces the target pixel.
  • "normal" β€” the fill pixels alpha value is used to combine it with the target pixel.
  • "multiply", "mult" β€” each channel of fill and target is multiplied, and the result is combined using the alpha channel of the fill pixel.
  • "dissolve" β€” if the alpha of the fill pixel is greater than a random number, the fill pixel is alpha combined with the target pixel.
  • "add" β€” the channels of the fill and target are added together, clamped to the range of the samples and alpha combined with the target.
  • "subtract" β€” the channels of the fill are subtracted from the target, clamped to be >= 0, and alpha combined with the target.
  • "diff" β€” the channels of the fill are subtracted from the target and the absolute value taken this is alpha combined with the target.
  • "lighten" β€” the higher value is taken from each channel of the fill and target pixels, which is then alpha combined with the target.
  • "darken" β€” the higher value is taken from each channel of the fill and target pixels, which is then alpha combined with the target.
  • "hue" β€” the combination of the saturation and value of the target is combined with the hue of the fill pixel, and is then alpha combined with the target.
  • "sat" β€” the combination of the hue and value of the target is combined with the saturation of the fill pixel, and is then alpha combined with the target.
  • "value" β€” the combination of the hue and value of the target is combined with the value of the fill pixel, and is then alpha combined with the target.
  • "color" β€” the combination of the value of the target is combined with the hue and saturation of the fill pixel, and is then alpha combined with the target.

combines()

Returns a list of possible combine types. Iconic.

πŸ’€ BUGS

box() does not support anti-aliasing yet. Default color is not unified yet.

πŸ‘‘ AUTHOR

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

🌸 SEE ALSO

Imager(3), Imager::Cookbook(3)

⭐ REVISION

$Revision$


Okay bestie, that's the whole page πŸ’– this was Imager::Draw(3pm) from perl v5.42.3, dated 2026-08-19 β€” now go forth and draw something gorgeous, mwah πŸŽ€βœ¨

πŸ“¦ where this page comes from