Imager::Files(3pm) | User Contributed Perl Documentation | Imager::Files(3pm) |
Imager::Files - working with image files
use Imager; my $img = ...; $img->write(file=>$filename, type=>$type) or die "Cannot write: ",$img->errstr; # type is optional if we can guess the format from the filename $img->write(file => "foo.png") or die "Cannot write: ",$img->errstr; $img = Imager->new; $img->read(file=>$filename, type=>$type) or die "Cannot read: ", $img->errstr; # type is optional if we can guess the type from the file data # and we normally can guess $img->read(file => $filename) or die "Cannot read: ", $img->errstr; Imager->write_multi({ file=> $filename, ... }, @images) or die "Cannot write: ", Imager->errstr; my @imgs = Imager->read_multi(file=>$filename) or die "Cannot read: ", Imager->errstr; Imager->set_file_limits(width=>$max_width, height=>$max_height) my @read_types = Imager->read_types; my @write_types = Imager->write_types; # we can write/write_multi to things other than filenames my $data; $img->write(data => \$data, type => $type) or die; open my $fh, "+>:raw", ... ; $img->write(fh => $fh, type => $type) or die; $img->write(fd => fileno($fh), type => $type) or die; # some file types need seek callbacks too $img->write(callback => \&write_callback, type => $type) or die; # and similarly for read/read_multi $img->read(data => $data) or die; $img->read(fh => $fh) or die; $img->read(fd => fileno($fh)) or die; $img->read(callback => \&read_callback) or die; use Imager 0.68; my $img = Imager->new(file => $filename) or die Imager->errstr; Imager->add_file_magic(name => $name, bits => $bits, mask => $mask);
You can read and write a variety of images formats, assuming you have the appropriate libraries, and images can be read or written to/from files, file handles, file descriptors, scalars, or through callbacks.
To see which image formats Imager is compiled to support the following code snippet is sufficient:
use Imager; print join " ", keys %Imager::formats;
This will include some other information identifying libraries rather than file formats. For new code you might find the "read_types()" or "write_types()" methods useful.
my $img = Imager->new; $img->read(file=>$filename, type=>$type) or die "Cannot read $filename: ", $img->errstr;
In most cases Imager can auto-detect the file type, so you can just supply the file name:
$img->read(file => $filename) or die "Cannot read $filename: ", $img->errstr;
The read() method accepts the "allow_incomplete" parameter. If this is non-zero then read() can return true on an incomplete image and set the "i_incomplete" tag.
From Imager 0.68 you can supply most read() parameters to the new() method to read the image file on creation. If the read fails, check Imager->errstr() for the cause:
use Imager 0.68; my $img = Imager->new(file => $filename) or die "Cannot read $filename: ", Imager->errstr;
$img->write(file=>$filename, type=>$type) or die "Cannot write $filename: ", $img->errstr;
my @imgs = Imager->read_multi(file=>$filename, type=>$type) or die "Cannot read $filename: ", Imager->errstr;
As with the read() method, Imager will normally detect the "type" automatically.
Imager->write_multi({ file=> $filename, type=>$type }, @images) or die "Cannot write $filename: ", Imager->errstr;
my @types = Imager->read_types;
These types are the possible values for the "type" parameter, not necessarily the extension of the files you're reading.
It is possible for extra file read handlers to be loaded when attempting to read a file, which may modify the list of available read types.
my @types = Imager->write_types;
Note that these are the possible values for the "type" parameter, not necessarily the extension of the files you're writing.
It is possible for extra file write handlers to be loaded when attempting to write a file, which may modify the list of available write types.
When writing, if the "filename" includes an extension that Imager recognizes, then you don't need the "type", but you may want to provide one anyway. See "Guessing types" for information on controlling this recognition.
The "type" parameter is a lowercase representation of the file type, and can be any of the following:
bmp Windows BitMaP (BMP) gif Graphics Interchange Format (GIF) jpeg JPEG/JFIF png Portable Network Graphics (PNG) pnm Portable aNyMap (PNM) raw Raw sgi SGI .rgb files tga TARGA tiff Tagged Image File Format (TIFF)
Support for other formats can be found on CPAN, including:
heif/heic Imager::File::HEIF qoi Imager::File::QOI webp Imager::File::WEBP
When you read an image, Imager may set some tags, possibly including information about the spatial resolution, textual information, and animation information. See "Tags" in Imager::ImageTypes for specifics.
The open() method is a historical alias for the read() method.
When reading or writing you can specify one of a variety of sources or targets:
# write in tiff format $image->write(file => "example.tif") or die $image->errstr; $image->write(file => 'foo.tmp', type => 'tiff') or die $image->errstr; my $image = Imager->new; $image->read(file => 'example.tif') or die $image->errstr;
Imager will set the handle to autoflush to make sure any buffered data is flushed , since Imager will write to the file descriptor (from fileno()) rather than writing at the perl level.
$image->write(fh => \*STDOUT, type => 'gif') or die $image->errstr; # for example, a file uploaded via CGI.pm $image->read(fd => $cgi->param('file')) or die $image->errstr;
If you get this from a perl file handle, you may need to flush any buffered output, otherwise it may appear in the output stream after the image.
$image->write(fd => file(STDOUT), type => 'gif') or die $image->errstr;
my $data; $image->write(data => \$data, type => 'tiff') or die $image->errstr; my $data = $row->{someblob}; # eg. from a database my @images = Imager->read_multi(data => $data) or die Imager->errstr; # from Imager 0.99 my @images = Imager->read_multi(data => \$data) or die Imager->errstr;
By default Imager will use buffered I/O when reading or writing an image. You can disabled buffering for output by supplying a "buffered => 0" parameter to "write()" or "write_multi()".
When reading from a file you can use either "callback" or "readcb" to supply the read callback, and when writing "callback" or "writecb" to supply the write callback.
Whether reading or writing a "TIFF" image, "seekcb" and "readcb" are required.
If a file handler attempts to use "readcb", "writecb" or "seekcb" and you haven't supplied one, the call will fail, failing the image read or write, returning an error message indicating that the callback is missing:
# attempting to read a TIFF image without a seekcb open my $fh, "<", $filename or die; my $rcb = sub { my $val; read($fh, $val, $_[0]) or return ""; return $val; }; my $im = Imager->new(callback => $rcb) or die Imager->errstr # dies with (wrapped here): # Error opening file: (Iolayer): Failed to read directory at offset 0: # (Iolayer): Seek error accessing TIFF directory: seek callback called # but no seekcb supplied
You can also provide a "closecb" parameter called when writing the file is complete. If no "closecb" is supplied the default will succeed silently.
# contrived my $data; sub mywrite { $data .= unpack("H*", shift); 1; } Imager->write_multi({ callback => \&mywrite, type => 'gif'}, @images) or die Imager->errstr;
"readcb"
The read callback is called with 2 parameters:
Your read callback should return the data as a scalar:
If your return value contains more data than "size" Imager will panic.
Your return value must not contain any characters over "\xFF" or Imager will panic.
"writecb"
Your write callback takes exactly one parameter, a scalar containing the data to be written.
Return true for success.
"seekcb"
The seek callback takes 2 parameters, a POSITION, and a WHENCE, defined in the same way as perl's seek function.
Previously you always needed a "seekcb" callback if you called Imager's "read()" or "read_multi()" without a "type" parameter, but this is no longer necessary unless the file handler requires seeking, such as for TIFF files.
Returns the new position in the file, or -1 on failure.
"closecb"
You can also supply a "closecb" which is called with no parameters when there is no more data to be written. This could be used to flush buffered data.
Return true on success.
When writing to a file, if you don't supply a "type" parameter Imager will attempt to guess it from the file name. This is done by calling the code reference stored in $Imager::FORMATGUESS. This is only done when write() or write_multi() is called with a "file" parameter, or if read() or read_multi() can't determine the type from the file's header.
The default function value of $Imager::FORMATGUESS is "\&Imager::def_guess_type".
Accepts a single parameter, the file name and returns the type or undef.
You can replace function with your own implementation if you have some specialized need. The function takes a single parameter, the name of the file, and should return either a file type or under.
# I'm writing jpegs to weird filenames local $Imager::FORMATGUESS = sub { 'jpeg' };
When reading a file Imager examines beginning of the file for identifying information. The current implementation attempts to detect the following image types beyond those supported by Imager:
You can now add to the magic database Imager uses for detecting file types:
Imager->add_file_magic(name => $name, bits => $bits, mask => $mask)
Adds to list of magic, the parameters are all required. The parameters are:
While mask is mostly a bit mask, some byte values are translated, the space character is treated as all zeros ("\x00"), and the "x" character as all ones ("\xFF").
New magic entries take priority over old entries.
You can add more than one magic entry for a given name.
Imager->add_file_magic(name => "heif", bits => " ftypheif" mask => " xxxxxxxx");
To set the limits, call the class method set_file_limits:
Imager->set_file_limits(width=>$max_width, height=>$max_height);
You can pass any or all of the limits above, any limits you do not pass are left as they were.
Any limit of zero for width or height is treated as unlimited.
A limit of zero for bytes is treated as one gigabyte, but higher bytes limits can be set explicitly.
By default, the width and height limits are zero, or unlimited. The default memory size limit is one gigabyte.
You can reset all limits to their defaults with the reset parameter:
# no limits Imager->set_file_limits(reset=>1);
This can be used with the other limits to reset all but the limit you pass:
# only width is limited Imager->set_file_limits(reset=>1, width=>100); # only bytes is limited Imager->set_file_limits(reset=>1, bytes=>10_000_000);
my ($max_width, $max_height, $max_bytes) = Imager->get_file_limits();
Parameters:
The different image formats can write different image type, and some have different options to control how the images are written.
When you call "write()" or "write_multi()" with an option that has the same name as a tag for the image format you're writing, then the value supplied to that option will be used to set the corresponding tag in the image. Depending on the image format, these values will be used when writing the image.
This replaces the previous options that were used when writing GIF images. Currently if you use an obsolete option, it will be converted to the equivalent tag and Imager will produced a warning. You can suppress these warnings by calling the "Imager::init()" function with the "warn_obsolete" option set to false:
Imager::init(warn_obsolete=>0);
At some point in the future these obsolete options will no longer be supported.
Imager can write "PGM" (Portable Gray Map) and "PPM" (Portable PixMaps) files, depending on the number of channels in the image. Currently the images are written in binary formats. Only 1 and 3 channel images can be written, including 1 and 3 channel paletted images.
$img->write(file=>'foo.ppm') or die $img->errstr;
Imager can read both the ASCII and binary versions of each of the "PBM" (Portable BitMap), "PGM" and "PPM" formats.
$img->read(file=>'foo.ppm') or die $img->errstr;
PNM does not support the spatial resolution tags.
The following tags are set when reading a PNM file:
The following tag is checked when writing an image with more than 8-bits/sample:
You can supply a "jpegquality" parameter ranging from 0 (worst quality) to 100 (best quality) when writing a JPEG file, which defaults to 75.
$img->write(file=>'foo.jpg', jpegquality=>90) or die $img->errstr;
If you write an image with an alpha channel to a JPEG file then it will be composed against the background set by the "i_background" parameter (or tag), or black if not supplied.
Imager will read a gray scale JPEG as a 1 channel image and a color JPEG as a 3 channel image.
$img->read(file=>'foo.jpg') or die $img->errstr;
The following tags are set in a JPEG image when read, and can be set to control output:
The "i_xres" and "i_yres" tags are expressed in pixels per inch no matter the value of this tag, they will be converted to/from the value stored in the JPEG file.
JPEG supports the spatial resolution tags "i_xres", "i_yres" and "i_aspect_only".
You can also set the following tags when writing to an image, they are not set in the image when reading:
use Imager::File::JPEG; my $prof = Imager::File::JPEG->is_mozjpeg ? "max" : "fastest"; $im->write(file => "foo.jpeg", jpeg_compress_profile => $prof) or die $im->errstr;
Note that unlike "MozJPEG", Imager always defaults to "fastest".
These set the same values as the "jpeg_base_quant_tbl_idx", "jpeg_lambda_log_scale1", "jpeg_lambda_log_scale2" and "jpeg_use_lambda_weight_tbl" tags, which can override the values set by "jpeg_tune".
Unlike "cjpeg" "-tune", "jpeg_tune" doesn't force the quality to 75.
Requires that Imager::File::JPEG was built with "MozJPEG".
"jpeg_jfif" - if set to zero, disable writing the JFIF header even if one is technically required, which it is for the color spaces Imager works with. This saves 18 bytes in the output file and most applications including web browsers will successfully read the file, but your experience may differ.
This will prevent the "i_xres", "i_yres" and "jpeg_density_units" tags from having an effect.
"jpeg_restart" - if set to a plain integer "N", generate a JPEG restart marker every "N" rows, if set to an integer followed by "B", generate a JPEG restart marker every "N" MCUs, the 8x8 pixel blocks that make up a JPEG image. Note that if this is specified in rows it will be translated to MCUs by "libjpeg".
This allows a decoder to recover from corruption, but it makes the file slightly larger.
Default: 0, no restart markers are produced.
"jpeg_sample" - control subsampling of the YCbCr components, equivalent to the "-sample" parameter for "cjpeg".
Default: "2x2,1x1,1x1", default 4:2:0 JPEG subsampling.
The following options can be set on writing with "MozJPEG" and correspond directly to the API options described in the "MozJPEG" README-mozilla.txt. Attempting to set them when Imager::File::JPEG has been built with another "libjpeg" will result in an error.
"jpeg_lambda_log_scale1", "jpeg_lambda_log_scale2", "jpeg_trellis_delta_dc_weight" - integer options.
"jpeg_trellis_freq_split", "jpeg_trellis_num_loops", "jpeg_base_quant_tbl_idx", "jpeg_dc_scan_opt_mode" - floating point options.
When reading a JPEG image, the following tag will be set, and ignored on writing:
If an "APP1" block containing EXIF information is found, then any of the following tags can be set when reading a JPEG image:
The following derived tags can also be set when reading a JPEG image:
The derived tags are for enumerated fields, when the value for the base field is valid then the text that appears in the EXIF specification for that value appears in the derived field. So for example if "exf_metering_mode" is 5 then "exif_metering_mode_name" is set to "Pattern".
eg.
my $image = Imager->new; $image->read(file => 'exiftest.jpg') or die "Cannot load image: ", $image->errstr; print $image->tags(name => "exif_image_description"), "\n"; print $image->tags(name => "exif_exposure_mode"), "\n"; print $image->tags(name => "exif_exposure_mode_name"), "\n"; # for the exiftest.jpg in the Imager distribution the output would be: Imager Development Notes 0 Auto exposure
Imager will not write EXIF tags to any type of image, if you need more advanced EXIF handling, consider Image::ExifTool.
Any future IPTC data decoding is likely to go into tags.
When writing one of more GIF images you can use the same Quantization Options as you can when converting an RGB image into a paletted image.
When reading a GIF all of the sub-images are combined using the screen size and image positions into one big image, producing an RGB image. This may change in the future to produce a paletted image where possible.
When you read a single GIF with "$img->read()" you can supply a reference to a scalar in the "colors" parameter, if the image is read the scalar will be filled with a reference to an anonymous array of Imager::Color objects, representing the palette of the image. This will be the first palette found in the image. If you want the palettes for each of the images in the file, use "read_multi()" and use the "getcolors()" method on each image.
GIF does not support the spatial resolution tags.
Imager will set the following tags in each image when reading, and can use most of them when writing to GIF:
Where applicable, the ("name") is the name of that field from the "GIF89" standard.
The following GIF writing options are obsolete, you should set the corresponding tag in the image, either by using the tags functions, or by supplying the tag and value as options.
Use "gif_local_map" in new code.
Use "gif_interlace" in new code.
Use "gif_delay" in new code.
New code should use the "gif_left" and "gif_top" tags.
This is currently unimplemented due to some limitations in "giflib".
You can supply a "page" parameter to the "read()" method to read some page other than the first. The page is 0 based:
# read the second image in the file $image->read(file=>"example.gif", page=>1) or die "Cannot read second page: ",$image->errstr,"\n";
Before release 0.46, Imager would read multiple image GIF image files into a single image, overlaying each of the images onto the virtual GIF screen.
As of 0.46 the default is to read the first image from the file, as if called with "page => 0".
You can return to the previous behavior by calling read with the "gif_consolidate" parameter set to a true value:
$img->read(file=>$some_gif_file, gif_consolidate=>1);
As with the to_paletted() method, if you supply a colors parameter as a reference to an array, this will be filled with Imager::Color objects of the color table generated for the image file.
Imager can write images to either paletted or RGB TIFF images, depending on the type of the source image.
When writing direct color images to TIFF the sample size of the output file depends on the input:
For paletted images:
If you are creating images for faxing you can set the class parameter set to "fax". By default the image is written in fine mode, but this can be overridden by setting the fax_fine parameter to zero. Since a fax image is bi-level, Imager uses a threshold to decide if a given pixel is black or white, based on a single channel. For gray scale images channel 0 is used, for color images channel 1 (green) is used. If you want more control over the conversion you can use $img->to_paletted() to product a bi-level image. This way you can use dithering:
my $bilevel = $img->to_paletted(make_colors => 'mono', translate => 'errdiff', errdiff => 'stucki');
Imager should be able to read any TIFF image you supply. Paletted TIFF images are read as paletted Imager images, since paletted TIFF images have 16-bits/sample (48-bits/color) this means the bottom 8-bits are lost, but this shouldn't be a big deal.
TIFF supports the spatial resolution tags. See the "tiff_resolutionunit" tag for some extra options.
As of Imager 0.62 Imager reads:
The following tags are set in a TIFF image when read, and can be set to control output:
On writing you can set this to either a numeric compression tag value, or one of the following values:
Ident Number Description none 1 No compression packbits 32773 Macintosh RLE ccittrle 2 CCITT RLE fax3 3 CCITT Group 3 fax encoding (T.4) t4 3 As above fax4 4 CCITT Group 4 fax encoding (T.6) t6 4 As above lzw 5 LZW jpeg 7 JPEG zip 8 Deflate (GZIP) Non-standard deflate 8 As above. oldzip 32946 Deflate with an older code. ccittrlew 32771 Word aligned CCITT RLE
In general a compression setting will be ignored where it doesn't make sense, eg. "jpeg" will be ignored for compression if the image is being written as bilevel.
Imager attempts to check that your build of "libtiff" supports the given compression, and will fallback to "packbits" if it isn't enabled. eg. older distributions didn't include LZW compression, and JPEG compression is only available if "libtiff" is configured with "libjpeg"'s location.
$im->write(file => 'foo.tif', tiff_compression => 'lzw') or die $im->errstr;
The "i_xres" and "i_yres" tags are expressed in pixels per inch no matter the value of this tag, they will be converted to/from the value stored in the TIFF file.
You can supply a "page" parameter to the "read()" method to read some page other than the first. The page is 0 based:
# read the second image in the file $image->read(file=>"example.tif", page=>1) or die "Cannot read second page: ",$image->errstr,"\n";
If you read an image with multiple alpha channels, then only the first alpha channel will be read.
When reading a "TIFF" image with callbacks, the "seekcb" callback parameter is also required.
When writing a "TIFF" image with callbacks, the "seekcb" and "readcb" parameters are also required.
"TIFF" is a random access file format, it cannot be read from or written to unseekable streams such as pipes or sockets.
Imager can write 24-bit RGB, and 8, 4 and 1-bit per pixel paletted Windows BMP files. Currently you cannot write compressed BMP files with Imager.
Imager can read 24-bit RGB, and 8, 4 and 1-bit perl pixel paletted Windows BMP files. There is some support for reading 16-bit per pixel images, but I haven't found any for testing.
BMP has no support for multiple image files.
BMP files support the spatial resolution tags, but since BMP has no support for storing only an aspect ratio, if "i_aspect_only" is set when you write the "i_xres" and "i_yres" values are scaled so the smaller is 72 DPI.
The following tags are set when you read an image from a BMP file:
When storing Targa images RLE compression can be activated with the "compress" parameter, the "idstring" parameter can be used to set the Targa comment field and the "wierdpack" option can be used to use the 15 and 16 bit Targa formats for RGB and RGBA data. The 15 bit format has 5 of each red, green and blue. The 16 bit format in addition allows 1 bit of alpha. The most significant bits are used for each channel.
Tags:
When reading raw images you need to supply the width and height of the image in the "xsize" and "ysize" options:
$img->read(file=>'foo.raw', xsize=>100, ysize=>100) or die "Cannot read raw image\n";
If your input file has more channels than you want, or (as is common), junk in the fourth channel, you can use the "raw_datachannels" and "raw_storechannels" options to control the number of channels in your input file and the resulting channels in your image. For example, if your input image uses 32-bits per pixel with red, green, blue and junk values for each pixel you could do:
$img->read(file=>'foo.raw', xsize => 100, ysize => 100, raw_datachannels => 4, raw_storechannels => 3, raw_interleave => 0) or die "Cannot read raw image\n";
In general, if you supply "raw_storechannels" you should also supply "raw_datachannels"
Read parameters:
012012012012
000011112222
This is the default.
Unfortunately, historically, the default "raw_interleave" for read has been 1, while writing only supports the "raw_interleave" = 0 format.
For future compatibility, you should always supply the "raw_interleave" (or "interleave") parameter. As of 0.68, Imager will warn if you attempt to read a raw image without a "raw_interleave" parameter.
$img->read(file=>'foo.raw', xsize=100, ysize=>100, raw_interleave=>1) or die "Cannot read raw image\n";
PNG Image modes
PNG files can be read and written in the following modes:
Unlike GIF, there is no automatic conversion to a paletted image, since PNG supports direct color.
PNG Text tags
Text tags are retrieved from and written to PNG "tEXT" or "zTXT" chunks. The following standard tags from the PNG specification are directly supported:
Each of these tags has a corresponding "base-tag-name_compressed" tag, eg. "png_comment_compressed". When reading, if the PNG chunk is compressed this tag will be set to 1, but is otherwise unset. When writing, Imager will honor the compression tag if set and non-zero, otherwise the chunk text will be compressed if the value is longer than 1000 characters, as recommended by the "libpng" documentation.
PNG "tEXT" or "zTXT" chunks outside of those above are read into or written from Imager tags named like:
Where N starts from 0. When writing both the "..._key" and "..._text" tags must be present or the write will fail. If the key or text do not satisfy the requirements above the write will fail.
Other PNG metadata tags
You can control the level of zlib compression used when writing with the "png_compression_level" parameter. This can be an integer between 0 (uncompressed) and 9 (best compression).
If you're using libpng 1.6 or later, or an earlier release configured with "PNG_BENIGN_ERRORS_SUPPORTED", you can choose to ignore file format errors the authors of libpng consider benign, this includes at least CRC errors and palette index overflows. Do this by supplying a true value for the "png_ignore_benign_errors" parameter to the read() method:
$im->read(file => "foo.png", png_ignore_benign_errors => 1) or die $im->errstr;
Icon and Cursor files are very similar, the only differences being a number in the header and the storage of the cursor hot spot. I've treated them separately so that you're not messing with tags to distinguish between them.
The following tags are set when reading an icon image and are used when writing it:
Rather than requiring a binary bitmap this is accepted in a specific format:
When reading an image, '.' is used as the 0 placeholder and '*' as the 1 placeholder. An example:
.* ..........................****** ..........................****** ..........................****** ..........................****** ...........................***** ............................**** ............................**** .............................*** .............................*** .............................*** .............................*** ..............................** ..............................** ...............................* ...............................* ................................ ................................ ................................ ................................ ................................ ................................ *............................... **.............................. **.............................. ***............................. ***............................. ****............................ ****............................ *****........................... *****........................... *****........................... *****...........................
The following tags are set when reading an icon:
For cursor files the following tags are set and read when reading and writing:
The following parameters can be supplied to read() or read_multi() to control reading of ICO/CUR files:
# retrieve the image as stored, without using the mask as an alpha # channel $img->read(file => 'foo.ico', ico_masked => 0) or die $img->errstr;
This was introduced in Imager 0.60. Previously reading ICO images acted as if "ico_masked => 0".
Note: If you get different results between "ico_alpha_masked" being set to 0 and 1, your mask may break when used with the Win32 API.
"cur_bits" is set when reading a cursor.
Examples:
my $img = Imager->new(xsize => 32, ysize => 32, channels => 4); $im->box(color => 'FF0000'); $im->write(file => 'box.ico'); $im->settag(name => 'cur_hotspotx', value => 16); $im->settag(name => 'cur_hotspoty', value => 16); $im->write(file => 'box.cur');
SGI images, often called by the extensions, RGB or BW, can be stored either uncompressed or compressed using an RLE compression.
By default, when saving to an extension of "rgb", "bw", "sgi", "rgba" the file will be saved in SGI format. The file extension is otherwise ignored, so saving a 3-channel image to a ".bw" file will result in a 3-channel image on disk.
The following tags are set when reading a SGI image:
To support a new format for reading, call the register_reader() class method:
Parameters:
This parameter is required.
The single parameter is required.
Example:
# from Imager::File::ICO Imager->register_reader ( type=>'ico', single => sub { my ($im, $io, %hsh) = @_; $im->{IMG} = i_readico_single($io, $hsh{page} || 0); unless ($im->{IMG}) { $im->_set_error(Imager->_error_as_msg); return; } return $im; }, multiple => sub { my ($io, %hsh) = @_; my @imgs = i_readico_multi($io); unless (@imgs) { Imager->_set_error(Imager->_error_as_msg); return; } return map { bless { IMG => $_, DEBUG => $Imager::DEBUG, ERRSTR => undef }, 'Imager' } @imgs; }, );
Parameters:
This parameter is required.
The single parameter is required.
Imager->add_type_extension(mytype => "mytype", "mytypish"); ... $im->write(file => "foo.mytypish") # use the mytype handler
If you name the reader module "Imager::File::"your-format-name where your-format-name is a fully upper case version of the type value you would pass to read(), read_multi(), write() or write_multi() then Imager will attempt to load that module if it has no other way to read or write that format.
For example, if you create a module Imager::File::GIF and the user has built Imager without it's normal GIF support then an attempt to read a GIF image will attempt to load Imager::File::GIF.
If your module can only handle reading then you can name your module "Imager::File::"your-format-name"Reader" and Imager will attempt to autoload it.
If your module can only handle writing then you can name your module "Imager::File::"your-format-name"Writer" and Imager will attempt to autoload it.
It isn't typically needed, but some cases where you might want to use it:
You probably don't need it.
If the module is not available no error occurs.
Preserves $@.
use Imager; Imager->preload;
Once you have an image the basic mechanism is:
# write an image from a CGI script # using CGI.pm use CGI qw(:standard); $| = 1; binmode STDOUT; print header(-type=>'image/gif'); $img->write(type=>'gif', fd=>fileno(STDOUT)) or die $img->errstr;
If you want to send a content length you can send the output to a scalar to get the length:
my $data; $img->write(type=>'gif', data=>\$data) or die $img->errstr; binmode STDOUT; print header(-type=>'image/gif', -content_length=>length($data)); print $data;
The basic idea is simple, just use write_multi():
my @imgs = ...; Imager->write_multi({ file=>$filename, type=>'gif' }, @imgs);
If your images are RGB images the default quantization mechanism will produce a very good result, but can take a long time to execute. You could either use the standard web color map:
Imager->write_multi({ file=>$filename, type=>'gif', make_colors=>'webmap' }, @imgs);
or use a median cut algorithm to built a fairly optimal color map:
Imager->write_multi({ file=>$filename, type=>'gif', make_colors=>'mediancut' }, @imgs);
By default all of the images will use the same global color map, which will produce a smaller image. If your images have significant color differences, you may want to generate a new palette for each image:
Imager->write_multi({ file=>$filename, type=>'gif', make_colors=>'mediancut', gif_local_map => 1 }, @imgs);
which will set the "gif_local_map" tag in each image to 1. Alternatively, if you know only some images have different colors, you can set the tag just for those images:
$imgs[2]->settag(name=>'gif_local_map', value=>1); $imgs[4]->settag(name=>'gif_local_map', value=>1);
and call write_multi() without a "gif_local_map" parameter, or supply an arrayref of values for the tag:
Imager->write_multi({ file=>$filename, type=>'gif', make_colors=>'mediancut', gif_local_map => [ 0, 0, 1, 0, 1 ] }, @imgs);
Other useful parameters include "gif_delay" to control the delay between frames and "transp" to control transparency.
This is pretty simple:
# print the author of a TIFF, if any my $img = Imager->new; $img->read(file=>$filename, type='tiff') or die $img->errstr; my $author = $img->tags(name=>'tiff_author'); if (defined $author) { print "Author: $author\n"; }
When saving GIF images the program does NOT try to shave off extra colors if it is possible. If you specify 128 colors and there are only 2 colors used - it will have a 128 color table anyway.
Tony Cook <tonyc@cpan.org>, Arnar M. Hrafnkelsson
2023-01-11 | perl v5.36.0 |