Imager::ImageTypes(3pm) | User Contributed Perl Documentation | Imager::ImageTypes(3pm) |
Imager::ImageTypes - image models for Imager
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"; }
Imager supports two basic models of image:
Direct color or paletted images can have 1 to 4 samples per color stored. Imager treats these as follows:
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 it's 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.
$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:
If not supplied then only placeholder object is created, which can be supplied to the "read()" or "img_set()" methods.
Note: you can use any Imager function on any sample size image.
Paletted images always use 8 bits/sample.
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.
my $im = Imager->new(file => $filename);
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->img_set(xsize=>500, ysize=>500, channels=>4);
This takes exactly the same parameters as the new() method, excluding those for reading from files.
These return basic attributes of an image object.
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.
print "Image height: ", $img->getheight(), "\n";
Same details apply as for "getwidth()".
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.
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.
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
This is 1 for grayscale images with alpha, 3 for RGB images with alpha and will return "undef" for all other images.
Returns an empty list if the image object is not initialized.
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.
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.
This may also be used for non-native Imager images in the future, for example, for an Imager object that draws on an SDL surface.
In scalar context, returns true if the image is bi-level.
In list context returns a list:
($is_bilevel, $zero_is_white) = $img->is_bilevel;
An image is considered bi-level, if all of the following are true:
If a real bi-level organization image is ever added to Imager, this function will return true for that too.
Returns an empty list if the image object is not initialized.
Direct images store the color value directly for each pixel in the image.
@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()" is used to fetch the current channel mask. The mask determines what channels are currently modifiable in the image. The channel mask is an integer value, if the "i-th" least significant bit is set the "i-th" channel is modifiable. eg. a channel mask of 0x5 means only channels 0 and 2 are writable.
Channel masks are deprecated.
$mask = $img->getmask(); $img->setmask(mask=>8); # modify alpha only ... $img->setmask(mask=>$mask); # restore previous mask
"setmask()" is used to set the channel mask of the image. See "getmask()" for details.
Channel masks are deprecated.
Paletted images keep an array of up to 256 colors, and each pixel is stored as an index into that array.
In general you can work with paletted images in the same way as RGB images, except that if you attempt to draw to a paletted image with a color that is not in the image's palette, the image will be converted to an RGB image. This means that drawing on a paletted image with anti-aliasing enabled will almost certainly convert the image to RGB.
Palette management takes place through "addcolors()", "setcolors()", "getcolors()" and "findcolor()":
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 the colors would overflow the palette.
The only parameter is "colors" which must be a reference to an array of Imager::Color objects.
$img->setcolors(start=>$start, colors=>\@colors);
Once you have colors in the palette you can overwrite them with the "setcolors()" method: "setcolors()" returns true on success.
Parameters:
# 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);
my $index = $img->findcolor(color=>$color);
which returns undef on failure, or the index of the color.
Parameter:
my $count = $img->colorcount;
my $maxcount = $img->maxcolors;
The amount of memory used by this is proportional to the number of colors present in the image, so to avoid using too much memory you can supply a maxcolors() parameter to limit the memory used.
Note: getcolorcount() treats the image as an 8-bit per sample image.
if (defined($img->getcolorcount(maxcolors=>512)) { print "Less than 512 colors in image\n"; }
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 is ignored. 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";
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";
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.
$palimg = $img->to_paletted(\%opts)
where %opts contains the options specified 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' });
$rgbimg = $img->to_rgb8;
No parameters.
$rgbimg = $img->to_rgb16;
No parameters.
$rgbimg = $img->to_rgb_double;
No parameters.
In the discussion below there are 3 image objects involved:
Parameters:
Masked images let you control which pixels are modified in an underlying image. Where the first channel is completely black in the mask image, writes to the underlying image are ignored.
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 is 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);
my @colors = Imager->make_palette(\%opts, @images);
You must supply at least one image, even if the "make_colors" parameter produces a fixed palette.
On failure returns no colors and you can check "Imager->errstr".
Image tags contain meta-data about the image, ie. information not stored as pixels of the image.
At the perl level each tag has a name or code and a value, which is an integer or an arbitrary string. An image can contain more than one tag with the same name or code, but having more than one tag with the same name is discouraged.
You can retrieve tags from an image using the tags() method, you can get all of 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 fairly limited, for access to pretty much all image metadata you may want to try Image::ExifTool.
With no parameters, retrieves a list array references, each containing a name and value: all 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 tags 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);
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 have a use for this please open an issue.
$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.
Setting or deleting tags by "code" is deprecated. If you have a use for this please open an issue.
Many tags are only meaningful for one format. GIF looping information is pretty useless for JPEG for example. Thus, many tags are set by only a single reader or used by a single writer. For a 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 various formats set some standard information.
# 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);
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().
This will only be used if the image has an alpha channel, and if there is space in the palette for a transparency color.
Other methods may be added in the future.
Possible values are:
It's possible other "translate" values will be added.
This documents the Imager initialization function, which you will almost never need to call.
This function is a mess, it can take the following named parameters:
Example:
Imager::init(log => 'trace.log', loglevel => 9);
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.
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();
No parameters.
Imager->close_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!");
Tony Cook <tonyc@cpan.org>, Arnar M. Hrafnkelsson
Imager(3), Imager::Files(3), Imager::Draw(3), Imager::Color(3), Imager::Fill(3), Imager::Font(3), Imager::Transformations(3), Imager::Engines(3), Imager::Filters(3), Imager::Expr(3), Imager::Matrix2d(3), Imager::Fountain(3)
2023-01-11 | perl v5.36.0 |