3 Imager::Files - working with image files
9 $img->write(file=>$filename, type=>$type)
10 or die "Cannot write: ",$img->errstr;
12 # type is optional if we can guess the format from the filename
13 $img->write(file => "foo.png")
14 or die "Cannot write: ",$img->errstr;
17 $img->read(file=>$filename, type=>$type)
18 or die "Cannot read: ", $img->errstr;
20 # type is optional if we can guess the type from the file data
21 # and we normally can guess
22 $img->read(file => $filename)
23 or die "Cannot read: ", $img->errstr;
25 Imager->write_multi({ file=> $filename, ... }, @images)
26 or die "Cannot write: ", Imager->errstr;
28 my @imgs = Imager->read_multi(file=>$filename)
29 or die "Cannot read: ", Imager->errstr;
31 Imager->set_file_limits(width=>$max_width, height=>$max_height)
33 my @read_types = Imager->read_types;
34 my @write_types = Imager->write_types;
36 # we can write/write_multi to things other than filenames
38 $img->write(data => \$data, type => $type) or die;
40 my $fh = ... ; # eg. IO::File
41 $img->write(fh => $fh, type => $type) or die;
43 $img->write(fd => fileno($fh), type => $type) or die;
45 # some file types need seek callbacks too
46 $img->write(callback => \&write_callback, type => $type) or die;
48 # and similarly for read/read_multi
49 $img->read(data => $data) or die;
50 $img->read(fh => $fh) or die;
51 $img->read(fd => fileno($fh)) or die;
52 $img->read(callback => \&read_callback) or die;
55 my $img = Imager->new(file => $filename)
56 or die Imager->errstr;
60 You can read and write a variety of images formats, assuming you have
61 the appropriate libraries, and images can be read or written to/from
62 files, file handles, file descriptors, scalars, or through callbacks.
64 To see which image formats Imager is compiled to support the following
65 code snippet is sufficient:
68 print join " ", keys %Imager::formats;
70 This will include some other information identifying libraries rather
71 than file formats. For new code you might find the L</read_types> or
72 L</write_types> methods useful.
78 Reading writing to and from files is simple, use the C<read()>
79 method to read an image:
81 my $img = Imager->new;
82 $img->read(file=>$filename, type=>$type)
83 or die "Cannot read $filename: ", $img->errstr;
85 In most cases Imager can auto-detect the file type, so you can just
88 $img->read(file => $filename)
89 or die "Cannot read $filename: ", $img->errstr;
91 The read() method accepts the C<allow_partial> parameter. If this is
92 non-zero then read() can return true on an incomplete image and set
93 the C<i_incomplete> tag.
95 From Imager 0.68 you can supply most read() parameters to the new()
96 method to read the image file on creation. If the read fails, check
97 Imager->errstr() for the cause:
100 my $img = Imager->new(file => $filename)
101 or die "Cannot read $filename: ", Imager->errstr;
105 and the C<write()> method to write an image:
107 $img->write(file=>$filename, type=>$type)
108 or die "Cannot write $filename: ", $img->errstr;
112 If you're reading from a format that supports multiple images per
113 file, use the C<read_multi()> method:
115 my @imgs = Imager->read_multi(file=>$filename, type=>$type)
116 or die "Cannot read $filename: ", Imager->errstr;
118 As with the read() method, Imager will normally detect the C<type>
123 and if you want to write multiple images to a single file use the
124 C<write_multi()> method:
126 Imager->write_multi({ file=> $filename, type=>$type }, @images)
127 or die "Cannot write $filename: ", Imager->errstr;
131 This is a class method that returns a list of the image file types
132 that Imager can read.
134 my @types = Imager->read_types;
136 These types are the possible values for the C<type> parameter, not
137 necessarily the extension of the files you're reading.
139 It is possible for extra file read handlers to be loaded when
140 attempting to read a file, which may modify the list of available read
145 This is a class method that returns a list of the image file types
146 that Imager can write.
148 my @types = Imager->write_types;
150 Note that these are the possible values for the C<type> parameter, not
151 necessarily the extension of the files you're writing.
153 It is possible for extra file write handlers to be loaded when
154 attempting to write a file, which may modify the list of available
159 When writing, if the I<filename> includes an extension that Imager
160 recognizes, then you don't need the I<type>, but you may want to
161 provide one anyway. See L</Guessing types> for information on
162 controlling this recognition.
164 The C<type> parameter is a lowercase representation of the file type,
165 and can be any of the following:
167 bmp Windows BitMaP (BMP)
168 gif Graphics Interchange Format (GIF)
170 png Portable Network Graphics (PNG)
171 pnm Portable aNyMap (PNM)
175 tiff Tagged Image File Format (TIFF)
177 When you read an image, Imager may set some tags, possibly including
178 information about the spatial resolution, textual information, and
179 animation information. See L<Imager::ImageTypes/Tags> for specifics.
181 The open() method is a historical alias for the read() method.
183 =head2 Input and output
185 When reading or writing you can specify one of a variety of sources or
192 file - The C<file> parameter is the name of the image file to be
193 written to or read from. If Imager recognizes the extension of the
194 file you do not need to supply a C<type>.
196 # write in tiff format
197 $image->write(file => "example.tif")
198 or die $image->errstr;
200 $image->write(file => 'foo.tmp', type => 'tiff')
201 or die $image->errstr;
203 my $image = Imager->new;
204 $image->read(file => 'example.tif')
205 or die $image->errstr;
209 fh - C<fh> is a file handle, typically either returned from
210 C<<IO::File->new()>>, or a glob from an C<open> call. You should call
211 C<binmode> on the handle before passing it to Imager.
213 Imager will set the handle to autoflush to make sure any buffered data
214 is flushed , since Imager will write to the file descriptor (from
215 fileno()) rather than writing at the perl level.
217 $image->write(fh => \*STDOUT, type => 'gif')
218 or die $image->errstr;
220 # for example, a file uploaded via CGI.pm
221 $image->read(fd => $cgi->param('file'))
222 or die $image->errstr;
226 fd - C<fd> is a file descriptor. You can get this by calling the
227 C<fileno()> function on a file handle, or by using one of the standard
228 file descriptor numbers.
230 If you get this from a perl file handle, you may need to flush any
231 buffered output, otherwise it may appear in the output stream after
234 $image->write(fd => file(STDOUT), type => 'gif')
235 or die $image->errstr;
239 data - When reading data, C<data> is a scalar containing the image
240 file data, when writing, C<data> is a reference to the scalar to save
241 the image file data too. For GIF images you will need giflib 4 or
242 higher, and you may need to patch giflib to use this option for
246 $image->write(data => \$data, type => 'tiff')
247 or die $image->errstr;
249 my $data = $row->{someblob}; # eg. from a database
250 my @images = Imager->read_multi(data => $data)
251 or die Imager->errstr;
255 callback - Imager will make calls back to your supplied coderefs to
256 read, write and seek from/to/through the image file.
258 When reading from a file you can use either C<callback> or C<readcb>
259 to supply the read callback, and when writing C<callback> or
260 C<writecb> to supply the write callback.
262 When writing you can also supply the C<maxbuffer> option to set the
263 maximum amount of data that will be buffered before your write
264 callback is called. Note: the amount of data supplied to your
265 callback can be smaller or larger than this size.
267 The read callback is called with 2 parameters, the minimum amount of
268 data required, and the maximum amount that Imager will store in it's C
269 level buffer. You may want to return the minimum if you have a slow
270 data source, or the maximum if you have a fast source and want to
271 prevent many calls to your perl callback. The read data should be
272 returned as a scalar.
274 Your write callback takes exactly one parameter, a scalar containing
275 the data to be written. Return true for success.
277 The seek callback takes 2 parameters, a I<POSITION>, and a I<WHENCE>,
278 defined in the same way as perl's seek function.
280 You can also supply a C<closecb> which is called with no parameters
281 when there is no more data to be written. This could be used to flush
287 $data .= unpack("H*", shift);
290 Imager->write_multi({ callback => \&mywrite, type => 'gif'}, @images)
291 or die Imager->errstr;
293 Note that for reading you'll almost always need to provide a
298 =head2 Guessing types
300 When writing to a file, if you don't supply a C<type> parameter Imager
301 will attempt to guess it from the filename. This is done by calling
302 the code reference stored in C<$Imager::FORMATGUESS>. This is only
303 done when write() or write_multi() is called with a C<file> parameter.
305 The default function value of C<$Imager::FORMATGUESS> is
306 C<\&Imager::def_guess_type>.
312 This is the default function Imager uses to derive a file type from a
313 file name. This is a function, not a method.
315 Accepts a single parameter, the filename and returns the type or
320 You can replace function with your own implementation if you have some
321 specialized need. The function takes a single parameter, the name of
322 the file, and should return either a file type or under.
324 # I'm writing jpegs to weird filenames
325 local $Imager::FORMATGUESS = sub { 'jpeg' };
327 When reading a file Imager examines beginning of the file for
328 identifying information. The current implementation attempts to
329 detect the following image types beyond those supported by Imager:
333 xpm, mng, jng, SGI RGB, ilbm, pcx, fits, psd (Photoshop), eps, Utah
338 =head2 Limiting the sizes of images you read
342 =item set_file_limits
344 In some cases you will be receiving images from an untested source,
345 such as submissions via CGI. To prevent such images from consuming
346 large amounts of memory, you can set limits on the dimensions of
347 images you read from files:
353 width - limit the width in pixels of the image
357 height - limit the height in pixels of the image
361 bytes - limits the amount of storage used by the image. This depends
362 on the width, height, channels and sample size of the image. For
363 paletted images this is calculated as if the image was expanded to a
368 To set the limits, call the class method set_file_limits:
370 Imager->set_file_limits(width=>$max_width, height=>$max_height);
372 You can pass any or all of the limits above, any limits you do not
373 pass are left as they were.
375 Any limit of zero is treated as unlimited.
377 By default, all of the limits are zero, or unlimited.
379 You can reset all of the limited to their defaults by passing in the
380 reset parameter as a true value:
383 Imager->set_file_limits(reset=>1);
385 This can be used with the other limits to reset all but the limit you
388 # only width is limited
389 Imager->set_file_limits(reset=>1, width=>100);
391 # only bytes is limited
392 Imager->set_file_limits(reset=>1, bytes=>10_000_000);
394 =item get_file_limits
396 You can get the current limits with the get_file_limits() method:
398 my ($max_width, $max_height, $max_bytes) =
399 Imager->get_file_limits();
403 =head1 TYPE SPECIFIC INFORMATION
405 The different image formats can write different image type, and some have
406 different options to control how the images are written.
408 When you call C<write()> or C<write_multi()> with an option that has
409 the same name as a tag for the image format you're writing, then the
410 value supplied to that option will be used to set the corresponding
411 tag in the image. Depending on the image format, these values will be
412 used when writing the image.
414 This replaces the previous options that were used when writing GIF
415 images. Currently if you use an obsolete option, it will be converted
416 to the equivalent tag and Imager will produced a warning. You can
417 suppress these warnings by calling the C<Imager::init()> function with
418 the C<warn_obsolete> option set to false:
420 Imager::init(warn_obsolete=>0);
422 At some point in the future these obsolete options will no longer be
425 =head2 PNM (Portable aNy Map)
427 Imager can write PGM (Portable Gray Map) and PPM (Portable PixMaps)
428 files, depending on the number of channels in the image. Currently
429 the images are written in binary formats. Only 1 and 3 channel images
430 can be written, including 1 and 3 channel paletted images.
432 $img->write(file=>'foo.ppm') or die $img->errstr;
434 Imager can read both the ASCII and binary versions of each of the PBM
435 (Portable BitMap), PGM and PPM formats.
437 $img->read(file=>'foo.ppm') or die $img->errstr;
439 PNM does not support the spatial resolution tags.
441 The following tags are set when reading a PNM file:
447 X<pnm_maxval>pnm_maxval - the maxvals number from the PGM/PPM header.
448 Always set to 2 for a PBM file.
452 X<pnm_type>pnm_type - the type number from the PNM header, 1 for ASCII
453 PBM files, 2 for ASCII PGM files, 3 for ASCII PPM files, 4 for binary
454 PBM files, 5 for binary PGM files, 6 for binary PPM files.
458 The following tag is checked when writing an image with more than
465 X<pnm_write_wide_data>pnm_write_wide_data - if this is non-zero then
466 write() can write PGM/PPM files with 16-bits/sample. Some
467 applications, for example GIMP 2.2, and tools can only read
468 8-bit/sample binary PNM files, so Imager will only write a 16-bit
469 image when this tag is non-zero.
475 You can supply a C<jpegquality> parameter (0-100) when writing a JPEG
476 file, which defaults to 75%. If you write an image with an alpha
477 channel to a jpeg file then it will be composited against the
478 background set by the C<i_background> parameter (or tag).
480 $img->write(file=>'foo.jpg', jpegquality=>90) or die $img->errstr;
482 Imager will read a grayscale JPEG as a 1 channel image and a color
483 JPEG as a 3 channel image.
485 $img->read(file=>'foo.jpg') or die $img->errstr;
487 The following tags are set in a JPEG image when read, and can be set
492 =item jpeg_density_unit
494 The value of the density unit field in the JFIF header. This is
495 ignored on writing if the C<i_aspect_only> tag is non-zero.
497 The C<i_xres> and C<i_yres> tags are expressed in pixels per inch no
498 matter the value of this tag, they will be converted to/from the value
499 stored in the JPEG file.
501 =item jpeg_density_unit_name
503 This is set when reading a JPEG file to the name of the unit given by
504 C<jpeg_density_unit>. Possible results include C<inch>,
505 C<centimeter>, C<none> (the C<i_aspect_only> tag is also set reading
506 these files). If the value of jpeg_density_unit is unknown then this
515 JPEG supports the spatial resolution tags C<i_xres>, C<i_yres> and
518 If an APP1 block containing EXIF information is found, then any of the
519 following tags can be set:
523 exif_aperture exif_artist exif_brightness exif_color_space
524 exif_contrast exif_copyright exif_custom_rendered exif_date_time
525 exif_date_time_digitized exif_date_time_original
526 exif_digital_zoom_ratio exif_exposure_bias exif_exposure_index
527 exif_exposure_mode exif_exposure_program exif_exposure_time
528 exif_f_number exif_flash exif_flash_energy exif_flashpix_version
529 exif_focal_length exif_focal_length_in_35mm_film
530 exif_focal_plane_resolution_unit exif_focal_plane_x_resolution
531 exif_focal_plane_y_resolution exif_gain_control exif_image_description
532 exif_image_unique_id exif_iso_speed_rating exif_make exif_max_aperture
533 exif_metering_mode exif_model exif_orientation exif_related_sound_file
534 exif_resolution_unit exif_saturation exif_scene_capture_type
535 exif_sensing_method exif_sharpness exif_shutter_speed exif_software
536 exif_spectral_sensitivity exif_sub_sec_time
537 exif_sub_sec_time_digitized exif_sub_sec_time_original
538 exif_subject_distance exif_subject_distance_range
539 exif_subject_location exif_tag_light_source exif_user_comment
540 exif_version exif_white_balance exif_x_resolution exif_y_resolution
544 The following derived tags can also be set:
548 exif_color_space_name exif_contrast_name exif_custom_rendered_name
549 exif_exposure_mode_name exif_exposure_program_name exif_flash_name
550 exif_focal_plane_resolution_unit_name exif_gain_control_name
551 exif_light_source_name exif_metering_mode_name
552 exif_resolution_unit_name exif_saturation_name
553 exif_scene_capture_type_name exif_sensing_method_name
554 exif_sharpness_name exif_subject_distance_range_name
555 exif_white_balance_name
559 The derived tags are for enumerated fields, when the value for the
560 base field is valid then the text that appears in the EXIF
561 specification for that value appears in the derived field. So for
562 example if C<exf_metering_mode> is C<5> then
563 C<exif_metering_mode_name> is set to C<Pattern>.
567 my $image = Imager->new;
568 $image->read(file => 'exiftest.jpg')
569 or die "Cannot load image: ", $image->errstr;
570 print $image->tags(name => "exif_image_description"), "\n";
571 print $image->tags(name => "exif_exposure_mode"), "\n";
572 print $image->tags(name => "exif_exposure_mode_name"), "\n";
574 # for the exiftest.jpg in the Imager distribution the output would be:
575 Imager Development Notes
583 Historically, Imager saves IPTC data when reading a JPEG image, the
584 parseiptc() method returns a list of key/value pairs resulting from a
585 simple decoding of that data.
587 Any future IPTC data decoding is likely to go into tags.
591 =head2 GIF (Graphics Interchange Format)
593 When writing one of more GIF images you can use the same
594 L<Quantization Options|Imager::ImageTypes> as you can when converting
595 an RGB image into a paletted image.
597 When reading a GIF all of the sub-images are combined using the screen
598 size and image positions into one big image, producing an RGB image.
599 This may change in the future to produce a paletted image where possible.
601 When you read a single GIF with C<$img-E<gt>read()> you can supply a
602 reference to a scalar in the C<colors> parameter, if the image is read
603 the scalar will be filled with a reference to an anonymous array of
604 L<Imager::Color> objects, representing the palette of the image. This
605 will be the first palette found in the image. If you want the
606 palettes for each of the images in the file, use C<read_multi()> and
607 use the C<getcolors()> method on each image.
609 GIF does not support the spatial resolution tags.
611 Imager will set the following tags in each image when reading, and can
612 use most of them when writing to GIF:
618 gif_left - the offset of the image from the left of the "screen"
619 ("Image Left Position")
623 gif_top - the offset of the image from the top of the "screen" ("Image
628 gif_interlace - non-zero if the image was interlaced ("Interlace
633 gif_screen_width, gif_screen_height - the size of the logical
634 screen. When writing this is used as the minimum. If any image being
635 written would extend beyond this then the screen size is extended.
636 ("Logical Screen Width", "Logical Screen Height").
640 gif_local_map - Non-zero if this image had a local color map. If set
641 for an image when writing the image is quantized separately from the
642 other images in the file.
646 gif_background - The index in the global colormap of the logical
647 screen's background color. This is only set if the current image uses
648 the global colormap. You can set this on write too, but for it to
649 choose the color you want, you will need to supply only paletted
650 images and set the C<gif_eliminate_unused> tag to 0.
654 gif_trans_index - The index of the color in the colormap used for
655 transparency. If the image has a transparency then it is returned as
656 a 4 channel image with the alpha set to zero in this palette entry.
657 This value is not used when writing. ("Transparent Color Index")
661 gif_trans_color - A reference to an Imager::Color object, which is the
662 colour to use for the palette entry used to represent transparency in
663 the palette. You need to set the transp option (see L<Quantization
664 options>) for this value to be used.
668 gif_delay - The delay until the next frame is displayed, in 1/100 of a
669 second. ("Delay Time").
673 gif_user_input - whether or not a user input is expected before
674 continuing (view dependent) ("User Input Flag").
678 gif_disposal - how the next frame is displayed ("Disposal Method")
682 gif_loop - the number of loops from the Netscape Loop extension. This
683 may be zero to loop forever.
687 gif_comment - the first block of the first gif comment before each
692 gif_eliminate_unused - If this is true, when you write a paletted
693 image any unused colors will be eliminated from its palette. This is
698 gif_colormap_size - the original size of the color map for the image.
699 The color map of the image may have been expanded to include out of
704 Where applicable, the ("name") is the name of that field from the GIF89
707 The following gif writing options are obsolete, you should set the
708 corresponding tag in the image, either by using the tags functions, or
709 by supplying the tag and value as options.
715 gif_each_palette - Each image in the gif file has it's own palette if
716 this is non-zero. All but the first image has a local colour table
717 (the first uses the global colour table.
719 Use C<gif_local_map> in new code.
723 interlace - The images are written interlaced if this is non-zero.
725 Use C<gif_interlace> in new code.
729 gif_delays - A reference to an array containing the delays between
730 images, in 1/100 seconds.
732 Use C<gif_delay> in new code.
736 gif_positions - A reference to an array of references to arrays which
737 represent screen positions for each image.
739 New code should use the C<gif_left> and C<gif_top> tags.
743 gif_loop_count - If this is non-zero the Netscape loop extension block
744 is generated, which makes the animation of the images repeat.
746 This is currently unimplemented due to some limitations in giflib.
750 You can supply a C<page> parameter to the C<read()> method to read
751 some page other than the first. The page is 0 based:
753 # read the second image in the file
754 $image->read(file=>"example.gif", page=>1)
755 or die "Cannot read second page: ",$image->errstr,"\n";
757 Before release 0.46, Imager would read multi-image GIF image files
758 into a single image, overlaying each of the images onto the virtual
761 As of 0.46 the default is to read the first image from the file, as if
762 called with C<< page => 0 >>.
764 You can return to the previous behaviour by calling read with the
765 C<gif_consolidate> parameter set to a true value:
767 $img->read(file=>$some_gif_file, gif_consolidate=>1);
769 As with the to_paletted() method, if you supply a colors parameter as
770 a reference to an array, this will be filled with Imager::Color
771 objects of the color table generated for the image file.
773 =head2 TIFF (Tagged Image File Format)
775 Imager can write images to either paletted or RGB TIFF images,
776 depending on the type of the source image. Currently if you write a
777 16-bit/sample or double/sample image it will be written as an
778 8-bit/sample image. Only 1 or 3 channel images can be written.
780 If you are creating images for faxing you can set the I<class>
781 parameter set to C<fax>. By default the image is written in fine
782 mode, but this can be overridden by setting the I<fax_fine> parameter
783 to zero. Since a fax image is bi-level, Imager uses a threshold to
784 decide if a given pixel is black or white, based on a single channel.
785 For greyscale images channel 0 is used, for color images channel 1
786 (green) is used. If you want more control over the conversion you can
787 use $img->to_paletted() to product a bi-level image. This way you can
790 my $bilevel = $img->to_paletted(make_colors => 'mono',
791 translate => 'errdiff',
792 errdiff => 'stucki');
798 If set to 'fax' the image will be written as a bi-level fax image.
802 By default when I<class> is set to 'fax' the image is written in fine
803 mode, you can select normal mode by setting I<fax_fine> to 0.
807 Imager should be able to read any TIFF image you supply. Paletted
808 TIFF images are read as paletted Imager images, since paletted TIFF
809 images have 16-bits/sample (48-bits/color) this means the bottom
810 8-bits are lost, but this shouldn't be a big deal. Currently all
811 direct color images are read at 8-bits/sample.
813 TIFF supports the spatial resolution tags. See the
814 C<tiff_resolutionunit> tag for some extra options.
816 As of Imager 0.62 Imager reads:
822 16-bit grey, RGB, or CMYK image, including a possible alpha channel as
823 a 16-bit/sample image.
827 32-bit grey, RGB image, including a possible alpha channel as a
832 bi-level images as paletted images containing only black and white,
833 which other formats will also write as bi-level.
837 tiled paletted images are now handled correctly
841 The following tags are set in a TIFF image when read, and can be set
846 =item tiff_compression
848 When reading an image this is set to the numeric value of the TIFF
851 On writing you can set this to either a numeric compression tag value,
852 or one of the following values:
854 Ident Number Description
855 none 1 No compression
856 packbits 32773 Macintosh RLE
858 fax3 3 CCITT Group 3 fax encoding (T.4)
860 fax4 4 CCITT Group 4 fax encoding (T.6)
864 zip 8 Deflate (GZIP) Non-standard
866 oldzip 32946 Deflate with an older code.
867 ccittrlew 32771 Word aligned CCITT RLE
869 In general a compression setting will be ignored where it doesn't make
870 sense, eg. C<jpeg> will be ignored for compression if the image is
871 being written as bilevel.
873 Imager attempts to check that your build of libtiff supports the given
874 compression, and will fallback to C<packbits> if it isn't enabled.
875 eg. older distributions didn't include LZW compression, and JPEG
876 compression is only available if libtiff is configured with libjpeg's
879 $im->write(file => 'foo.tif', tiff_compression => 'lzw')
882 =item tiff_jpegquality
884 If I<tiff_compression> if C<jpeg> then this can be a number from 1 to
885 100 giving the JPEG compression quality. High values are better
886 quality and larger files.
888 =item tiff_resolutionunit
890 The value of the ResolutionUnit tag. This is ignored on writing if
891 the i_aspect_only tag is non-zero.
893 The C<i_xres> and C<i_yres> tags are expressed in pixels per inch no
894 matter the value of this tag, they will be converted to/from the value
895 stored in the TIFF file.
897 =item tiff_resolutionunit_name
899 This is set when reading a TIFF file to the name of the unit given by
900 C<tiff_resolutionunit>. Possible results include C<inch>,
901 C<centimeter>, C<none> (the C<i_aspect_only> tag is also set reading
902 these files) or C<unknown>.
904 =item tiff_bitspersample
906 Bits per sample from the image. This value is not used when writing
907 an image, it is only set on a read image.
909 =item tiff_photometric
911 Value of the PhotometricInterpretation tag from the image. This value
912 is not used when writing an image, it is only set on a read image.
914 =item tiff_documentname
916 =item tiff_imagedescription
930 =item tiff_hostcomputer
932 Various strings describing the image. tiff_datetime must be formatted
933 as "YYYY:MM:DD HH:MM:SS". These correspond directly to the mixed case
934 names in the TIFF specification. These are set in images read from a
935 TIFF and saved when writing a TIFF image.
939 You can supply a C<page> parameter to the C<read()> method to read
940 some page other than the first. The page is 0 based:
942 # read the second image in the file
943 $image->read(file=>"example.tif", page=>1)
944 or die "Cannot read second page: ",$image->errstr,"\n";
946 Note: Imager uses the TIFF*RGBA* family of libtiff functions,
947 unfortunately these don't support alpha channels on CMYK images. This
948 will result in a full coverage alpha channel on CMYK images with an
949 alpha channel, until this is implemented in libtiff (or Imager's TIFF
950 implementation changes.)
952 If you read an image with multiple alpha channels, then only the first
953 alpha channel will be read.
955 Currently Imager's TIFF support reads all direct color images as 8-bit
956 RGB images, this may change in the future to reading 16-bit/sample
959 Currently tags that control the output color type and compression are
960 ignored when writing, this may change in the future. If you have
961 processes that rely upon Imager always producing packbits compressed
962 RGB images, you should strip any tags before writing.
966 Imager can write 24-bit RGB, and 8, 4 and 1-bit per pixel paletted
967 Windows BMP files. Currently you cannot write compressed BMP files
970 Imager can read 24-bit RGB, and 8, 4 and 1-bit perl pixel paletted
971 Windows BMP files. There is some support for reading 16-bit per pixel
972 images, but I haven't found any for testing.
974 BMP has no support for multi-image files.
976 BMP files support the spatial resolution tags, but since BMP has no
977 support for storing only an aspect ratio, if C<i_aspect_only> is set
978 when you write the C<i_xres> and C<i_yres> values are scaled so the
981 The following tags are set when you read an image from a BMP file:
985 =item bmp_compression
987 The type of compression, if any. This can be any of the following
998 8-bits/pixel paletted value RLE compression.
1002 4-bits/pixel paletted value RLE compression.
1004 =item BI_BITFIELDS (3)
1010 =item bmp_compression_name
1012 The bmp_compression value as a BI_* string
1014 =item bmp_important_colors
1016 The number of important colors as defined by the writer of the image.
1018 =item bmp_used_colors
1020 Number of color used from the BMP header
1024 The file size from the BMP header
1028 Number of bits stored per pixel. (24, 8, 4 or 1)
1034 When storing targa images rle compression can be activated with the
1035 'compress' parameter, the 'idstring' parameter can be used to set the
1036 targa comment field and the 'wierdpack' option can be used to use the
1037 15 and 16 bit targa formats for rgb and rgba data. The 15 bit format
1038 has 5 of each red, green and blue. The 16 bit format in addition
1039 allows 1 bit of alpha. The most significant bits are used for each
1057 When reading raw images you need to supply the width and height of the
1058 image in the xsize and ysize options:
1060 $img->read(file=>'foo.raw', xsize=>100, ysize=>100)
1061 or die "Cannot read raw image\n";
1063 If your input file has more channels than you want, or (as is common),
1064 junk in the fourth channel, you can use the datachannels and
1065 storechannels options to control the number of channels in your input
1066 file and the resulting channels in your image. For example, if your
1067 input image uses 32-bits per pixel with red, green, blue and junk
1068 values for each pixel you could do:
1070 $img->read(file=>'foo.raw', xsize=>100, ysize=>100, datachannels=>4,
1072 or die "Cannot read raw image\n";
1080 raw_interleave - controls the ordering of samples within the image.
1081 Default: 1. Alternatively and historically spelled C<interleave>.
1088 0 - samples are pixel by pixel, so all samples for the first pixel,
1089 then all samples for the second pixel and so on. eg. for a four pixel
1090 scanline the channels would be laid out as:
1096 1 - samples are line by line, so channel 0 for the entire scanline is
1097 followed by channel 1 for the entire scanline and so on. eg. for a
1098 four pixel scanline the channels would be laid out as:
1102 This is the default.
1106 Unfortunately, historically, the default C<raw_interleave> for read
1107 has been 1, while writing only supports the C<raw_interleave> = 0
1110 For future compatibility, you should always supply the
1111 C<raw_interleave> (or C<interleave>) parameter. As of 0.68, Imager
1112 will warn if you attempt to read a raw image without a
1113 C<raw_interleave> parameter.
1117 raw_storechannels - the number of channels to store in the image.
1118 Range: 1 to 4. Default: 3. Alternatively and historically spelled
1123 raw_datachannels - the number of channels to read from the file.
1124 Range: 1 or more. Default: 3. Alternatively and historically spelled
1129 $img->read(file=>'foo.raw', xsize=100, ysize=>100, raw_interleave=>1)
1130 or die "Cannot read raw image\n";
1134 There are no PNG specific tags.
1136 =head2 ICO (Microsoft Windows Icon) and CUR (Microsoft Windows Cursor)
1138 Icon and Cursor files are very similar, the only differences being a
1139 number in the header and the storage of the cursor hotspot. I've
1140 treated them separately so that you're not messing with tags to
1141 distinguish between them.
1143 The following tags are set when reading an icon image and are used
1150 This is the AND mask of the icon. When used as an icon in Windows 1
1151 bits in the mask correspond to pixels that are modified by the source
1152 image rather than simply replaced by the source image.
1154 Rather than requiring a binary bitmap this is accepted in a specific format:
1160 first line consisting of the 0 placeholder, the 1 placeholder and a
1165 following lines which contain 0 and 1 placeholders for each scanline
1166 of the image, starting from the top of the image.
1170 When reading an image, '.' is used as the 0 placeholder and '*' as the
1171 1 placeholder. An example:
1174 ..........................******
1175 ..........................******
1176 ..........................******
1177 ..........................******
1178 ...........................*****
1179 ............................****
1180 ............................****
1181 .............................***
1182 .............................***
1183 .............................***
1184 .............................***
1185 ..............................**
1186 ..............................**
1187 ...............................*
1188 ...............................*
1189 ................................
1190 ................................
1191 ................................
1192 ................................
1193 ................................
1194 ................................
1195 *...............................
1196 **..............................
1197 **..............................
1198 ***.............................
1199 ***.............................
1200 ****............................
1201 ****............................
1202 *****...........................
1203 *****...........................
1204 *****...........................
1205 *****...........................
1209 The following tags are set when reading an icon:
1215 The number of bits per pixel used to store the image.
1219 For cursor files the following tags are set and read when reading and
1226 This is the same as the ico_mask above.
1232 The "hot" spot of the cursor image. This is the spot on the cursor
1233 that you click with. If you set these to out of range values they are
1234 clipped to the size of the image when written to the file.
1238 The following parameters can be supplied to read() or read_multi() to
1239 control reading of ICO/CUR files:
1245 ico_masked - if true, the default, then the icon/cursors mask is
1246 applied as an alpha channel to the image. This may result in a
1247 paletted image being returned as a direct color image. Default: 1
1249 # retrieve the image as stored, without using the mask as an alpha
1251 $img->read(file => 'foo.ico', ico_masked => 0)
1252 or die $img->errstr;
1254 This was introduced in Imager 0.60. Previously reading ICO images
1255 acted as if C<ico_masked =E<gt> 0>.
1259 C<cur_bits> is set when reading a cursor.
1263 my $img = Imager->new(xsize => 32, ysize => 32, channels => 4);
1264 $im->box(color => 'FF0000');
1265 $im->write(file => 'box.ico');
1267 $im->settag(name => 'cur_hotspotx', value => 16);
1268 $im->settag(name => 'cur_hotspoty', value => 16);
1269 $im->write(file => 'box.cur');
1271 =head2 SGI (RGB, BW)
1273 SGI images, often called by the extensions, RGB or BW, can be stored
1274 either uncompressed or compressed using an RLE compression.
1276 By default, when saving to an extension of C<rgb>, C<bw>, C<sgi>,
1277 C<rgba> the file will be saved in SGI format. The file extension is
1278 otherwise ignored, so saving a 3-channel image to a C<.bw> file will
1279 result in a 3-channel image on disk.
1281 The following tags are set when reading a SGI image:
1287 i_comment - the IMAGENAME field from the image. Also written to the
1292 sgi_pixmin, sgi_pixmax - the PIXMIN and PIXMAX fields from the image.
1293 On reading image data is expanded from this range to the full range of
1294 samples in the image.
1298 sgi_bpc - the number of bytes per sample for the image. Ignored when
1303 sgi_rle - whether or not the image is compressed. If this is non-zero
1304 when writing the image will be compressed.
1308 =head1 ADDING NEW FORMATS
1310 To support a new format for reading, call the register_reader() class
1315 =item register_reader
1317 Registers single or multiple image read functions.
1325 type - the identifier of the file format, if Imager's
1326 i_test_format_probe() can identify the format then this value should
1327 match i_test_format_probe()'s result.
1329 This parameter is required.
1333 single - a code ref to read a single image from a file. This is
1340 the object that read() was called on,
1344 an Imager::IO object that should be used to read the file, and
1348 all the parameters supplied to the read() method.
1352 The single parameter is required.
1356 multiple - a code ref which is called to read multiple images from a
1357 file. This is supplied:
1363 an Imager::IO object that should be used to read the file, and
1367 all the parameters supplied to the read_multi() method.
1375 # from Imager::File::ICO
1376 Imager->register_reader
1381 my ($im, $io, %hsh) = @_;
1382 $im->{IMG} = i_readico_single($io, $hsh{page} || 0);
1384 unless ($im->{IMG}) {
1385 $im->_set_error(Imager->_error_as_msg);
1392 my ($io, %hsh) = @_;
1394 my @imgs = i_readico_multi($io);
1396 Imager->_set_error(Imager->_error_as_msg);
1400 bless { IMG => $_, DEBUG => $Imager::DEBUG, ERRSTR => undef }, 'Imager'
1405 =item register_writer
1407 Registers single or multiple image write functions.
1415 type - the identifier of the file format. This is typically the
1416 extension in lowercase.
1418 This parameter is required.
1422 single - a code ref to write a single image to a file. This is
1429 the object that write() was called on,
1433 an Imager::IO object that should be used to write the file, and
1437 all the parameters supplied to the write() method.
1441 The single parameter is required.
1445 multiple - a code ref which is called to write multiple images to a
1446 file. This is supplied:
1452 the class name write_multi() was called on, this is typically
1457 an Imager::IO object that should be used to write the file, and
1461 all the parameters supplied to the read_multi() method.
1469 If you name the reader module C<Imager::File::>I<your-format-name>
1470 where I<your-format-name> is a fully upper case version of the type
1471 value you would pass to read(), read_multi(), write() or write_multi()
1472 then Imager will attempt to load that module if it has no other way to
1473 read or write that format.
1475 For example, if you create a module Imager::File::GIF and the user has
1476 built Imager without it's normal GIF support then an attempt to read a
1477 GIF image will attempt to load Imager::File::GIF.
1479 If your module can only handle reading then you can name your module
1480 C<Imager::File::>I<your-format-name>C<Reader> and Imager will attempt
1483 If your module can only handle writing then you can name your module
1484 C<Imager::File::>I<your-format-name>C<Writer> and Imager will attempt
1489 =head2 Producing an image from a CGI script
1491 Once you have an image the basic mechanism is:
1497 set STDOUT to autoflush
1501 output a content-type header, and optionally a content-length header
1505 put STDOUT into binmode
1509 call write() with the C<fd> or C<fh> parameter. You will need to
1510 provide the C<type> parameter since Imager can't use the extension to
1511 guess the file format you want.
1515 # write an image from a CGI script
1517 use CGI qw(:standard);
1520 print header(-type=>'image/gif');
1521 $img->write(type=>'gif', fd=>fileno(STDOUT))
1522 or die $img->errstr;
1524 If you want to send a content length you can send the output to a
1525 scalar to get the length:
1528 $img->write(type=>'gif', data=>\$data)
1529 or die $img->errstr;
1531 print header(-type=>'image/gif', -content_length=>length($data));
1534 =head2 Writing an animated GIF
1536 The basic idea is simple, just use write_multi():
1539 Imager->write_multi({ file=>$filename, type=>'gif' }, @imgs);
1541 If your images are RGB images the default quantization mechanism will
1542 produce a very good result, but can take a long time to execute. You
1543 could either use the standard webmap:
1545 Imager->write_multi({ file=>$filename,
1547 make_colors=>'webmap' },
1550 or use a median cut algorithm to built a fairly optimal color map:
1552 Imager->write_multi({ file=>$filename,
1554 make_colors=>'mediancut' },
1557 By default all of the images will use the same global colormap, which
1558 will produce a smaller image. If your images have significant color
1559 differences, you may want to generate a new palette for each image:
1561 Imager->write_multi({ file=>$filename,
1563 make_colors=>'mediancut',
1564 gif_local_map => 1 },
1567 which will set the C<gif_local_map> tag in each image to 1.
1568 Alternatively, if you know only some images have different colors, you
1569 can set the tag just for those images:
1571 $imgs[2]->settag(name=>'gif_local_map', value=>1);
1572 $imgs[4]->settag(name=>'gif_local_map', value=>1);
1574 and call write_multi() without a C<gif_local_map> parameter, or supply
1575 an arrayref of values for the tag:
1577 Imager->write_multi({ file=>$filename,
1579 make_colors=>'mediancut',
1580 gif_local_map => [ 0, 0, 1, 0, 1 ] },
1583 Other useful parameters include C<gif_delay> to control the delay
1584 between frames and C<transp> to control transparency.
1586 =head2 Reading tags after reading an image
1588 This is pretty simple:
1590 # print the author of a TIFF, if any
1591 my $img = Imager->new;
1592 $img->read(file=>$filename, type='tiff') or die $img->errstr;
1593 my $author = $img->tags(name=>'tiff_author');
1594 if (defined $author) {
1595 print "Author: $author\n";
1600 When saving Gif images the program does NOT try to shave of extra
1601 colors if it is possible. If you specify 128 colors and there are
1602 only 2 colors used - it will have a 128 colortable anyway.