3 Imager::Files - working with image files
8 $img->write(file=>$filename, type=>$type)
9 or die "Cannot write: ",$img->errstr;
12 $img->read(file=>$filename, type=>$type)
13 or die "Cannot read: ", $img->errstr;
15 Imager->write_multi({ file=> $filename, ... }, @images)
16 or die "Cannot write: ", Imager->errstr;
18 my @imgs = Imager->read_multi(file=>$filename)
19 or die "Cannot read: ", Imager->errstr;
21 Imager->set_file_limits(width=>$max_width, height=>$max_height)
23 my @read_types = Imager->read_types;
24 my @write_types = Imager->write_types;
28 You can read and write a variety of images formats, assuming you have
29 the appropriate libraries, and images can be read or written to/from
30 files, file handles, file descriptors, scalars, or through callbacks.
32 To see which image formats Imager is compiled to support the following
33 code snippet is sufficient:
36 print join " ", keys %Imager::formats;
38 This will include some other information identifying libraries rather
39 than file formats. For new code you might find the L</read_types> or
40 L</write_types> methods useful.
46 Reading writing to and from files is simple, use the C<read()>
47 method to read an image:
49 my $img = Imager->new;
50 $img->read(file=>$filename, type=>$type)
51 or die "Cannot read $filename: ", $img->errstr;
53 In most cases Imager can auto-detect the file type, so you can just
56 $img->read(file => $filename)
57 or die "Cannot read $filename: ", $img->errstr;
59 The read() method accepts the C<allow_partial> parameter. If this is
60 non-zero then read() can return true on an incomplete image and set
61 the C<i_incomplete> tag.
65 and the C<write()> method to write an image:
67 $img->write(file=>$filename, type=>$type)
68 or die "Cannot write $filename: ", $img->errstr;
72 If you're reading from a format that supports multiple images per
73 file, use the C<read_multi()> method:
75 my @imgs = Imager->read_multi(file=>$filename, type=>$type)
76 or die "Cannot read $filename: ", Imager->errstr;
78 As with the read() method, Imager will normally detect the C<type>
83 and if you want to write multiple images to a single file use the
84 C<write_multi()> method:
86 Imager->write_multi({ file=> $filename, type=>$type }, @images)
87 or die "Cannot write $filename: ", Imager->errstr;
91 This is a class method that returns a list of the image file types
94 my @types = Imager->read_types;
96 These types are the possible values for the C<type> parameter, not
97 necessarily the extension of the files you're reading.
99 It is possible for extra file read handlers to be loaded when
100 attempting to read a file, which may modify the list of available read
105 This is a class method that returns a list of the image file types
106 that Imager can write.
108 my @types = Imager->write_types;
110 Note that these are the possible values for the C<type> parameter, not
111 necessarily the extension of the files you're writing.
113 It is possible for extra file write handlers to be loaded when
114 attempting to write a file, which may modify the list of available
119 When writing, if the I<filename> includes an extension that Imager
120 recognizes, then you don't need the I<type>, but you may want to
121 provide one anyway. See L</Guessing types> for information on
122 controlling this recognition.
124 The C<type> parameter is a lowercase representation of the file type,
125 and can be any of the following:
127 bmp Windows BitMaP (BMP)
128 gif Graphics Interchange Format (GIF)
130 png Portable Network Graphics (PNG)
131 pnm Portable aNyMap (PNM)
135 tiff Tagged Image File Format (TIFF)
137 When you read an image, Imager may set some tags, possibly including
138 information about the spatial resolution, textual information, and
139 animation information. See L<Imager::ImageTypes/Tags> for specifics.
141 The open() method is a historical alias for the read() method.
143 =head2 Input and output
145 When reading or writing you can specify one of a variety of sources or
152 file - The C<file> parameter is the name of the image file to be
153 written to or read from. If Imager recognizes the extension of the
154 file you do not need to supply a C<type>.
156 # write in tiff format
157 $image->write(file => "example.tif")
158 or die $image->errstr;
160 $image->write(file => 'foo.tmp', type => 'tiff')
161 or die $image->errstr;
163 my $image = Imager->new;
164 $image->read(file => 'example.tif')
165 or die $image->errstr;
169 fh - C<fh> is a file handle, typically either returned from
170 C<<IO::File->new()>>, or a glob from an C<open> call. You should call
171 C<binmode> on the handle before passing it to Imager.
173 Imager will set the handle to autoflush to make sure any buffered data
174 is flushed , since Imager will write to the file descriptor (from
175 fileno()) rather than writing at the perl level.
177 $image->write(fh => \*STDOUT, type => 'gif')
178 or die $image->errstr;
180 # for example, a file uploaded via CGI.pm
181 $image->read(fd => $cgi->param('file'))
182 or die $image->errstr;
186 fd - C<fd> is a file descriptor. You can get this by calling the
187 C<fileno()> function on a file handle, or by using one of the standard
188 file descriptor numbers.
190 If you get this from a perl file handle, you may need to flush any
191 buffered output, otherwise it may appear in the output stream after
194 $image->write(fd => file(STDOUT), type => 'gif')
195 or die $image->errstr;
199 data - When reading data, C<data> is a scalar containing the image
200 file data, when writing, C<data> is a reference to the scalar to save
201 the image file data too. For GIF images you will need giflib 4 or
202 higher, and you may need to patch giflib to use this option for
206 $image->write(data => \$data, type => 'tiff')
207 or die $image->errstr;
209 my $data = $row->{someblob}; # eg. from a database
210 my @images = Imager->read_multi(data => $data)
211 or die Imager->errstr;
215 callback - Imager will make calls back to your supplied coderefs to
216 read, write and seek from/to/through the image file.
218 When reading from a file you can use either C<callback> or C<readcb>
219 to supply the read callback, and when writing C<callback> or
220 C<writecb> to supply the write callback.
222 When writing you can also supply the C<maxbuffer> option to set the
223 maximum amount of data that will be buffered before your write
224 callback is called. Note: the amount of data supplied to your
225 callback can be smaller or larger than this size.
227 The read callback is called with 2 parameters, the minimum amount of
228 data required, and the maximum amount that Imager will store in it's C
229 level buffer. You may want to return the minimum if you have a slow
230 data source, or the maximum if you have a fast source and want to
231 prevent many calls to your perl callback. The read data should be
232 returned as a scalar.
234 Your write callback takes exactly one parameter, a scalar containing
235 the data to be written. Return true for success.
237 The seek callback takes 2 parameters, a I<POSITION>, and a I<WHENCE>,
238 defined in the same way as perl's seek function.
240 You can also supply a C<closecb> which is called with no parameters
241 when there is no more data to be written. This could be used to flush
247 $data .= unpack("H*", shift);
250 Imager->write_multi({ callback => \&mywrite, type => 'gif'}, @images)
251 or die Imager->errstr;
253 Note that for reading you'll almost always need to provide a
258 =head2 Guessing types
260 When writing to a file, if you don't supply a C<type> parameter Imager
261 will attempt to guess it from the filename. This is done by calling
262 the code reference stored in C<$Imager::FORMATGUESS>. This is only
263 done when write() or write_multi() is called with a C<file> parameter.
265 The default function value of C<$Imager::FORMATGUESS> is
266 C<\&Imager::def_guess_type>.
272 This is the default function Imager uses to derive a file type from a
273 file name. This is a function, not a method.
275 Accepts a single parameter, the filename and returns the type or
280 You can replace function with your own implementation if you have some
281 specialized need. The function takes a single parameter, the name of
282 the file, and should return either a file type or under.
284 # I'm writing jpegs to weird filenames
285 local $Imager::FORMATGUESS = sub { 'jpeg' };
287 When reading a file Imager examines beginning of the file for
288 identifying information. The current implementation attempts to
289 detect the following image types beyond those supported by Imager:
293 xpm, mng, jng, SGI RGB, ilbm, pcx, fits, psd (Photoshop), eps, Utah
298 =head2 Limiting the sizes of images you read
302 =item set_file_limits
304 In some cases you will be receiving images from an untested source,
305 such as submissions via CGI. To prevent such images from consuming
306 large amounts of memory, you can set limits on the dimensions of
307 images you read from files:
313 width - limit the width in pixels of the image
317 height - limit the height in pixels of the image
321 bytes - limits the amount of storage used by the image. This depends
322 on the width, height, channels and sample size of the image. For
323 paletted images this is calculated as if the image was expanded to a
328 To set the limits, call the class method set_file_limits:
330 Imager->set_file_limits(width=>$max_width, height=>$max_height);
332 You can pass any or all of the limits above, any limits you do not
333 pass are left as they were.
335 Any limit of zero is treated as unlimited.
337 By default, all of the limits are zero, or unlimited.
339 You can reset all of the limited to their defaults by passing in the
340 reset parameter as a true value:
343 Imager->set_file_limits(reset=>1);
345 This can be used with the other limits to reset all but the limit you
348 # only width is limited
349 Imager->set_file_limits(reset=>1, width=>100);
351 # only bytes is limited
352 Imager->set_file_limits(reset=>1, bytes=>10_000_000);
354 =item get_file_limits
356 You can get the current limits with the get_file_limits() method:
358 my ($max_width, $max_height, $max_bytes) =
359 Imager->get_file_limits();
363 =head1 TYPE SPECIFIC INFORMATION
365 The different image formats can write different image type, and some have
366 different options to control how the images are written.
368 When you call C<write()> or C<write_multi()> with an option that has
369 the same name as a tag for the image format you're writing, then the
370 value supplied to that option will be used to set the corresponding
371 tag in the image. Depending on the image format, these values will be
372 used when writing the image.
374 This replaces the previous options that were used when writing GIF
375 images. Currently if you use an obsolete option, it will be converted
376 to the equivalent tag and Imager will produced a warning. You can
377 suppress these warnings by calling the C<Imager::init()> function with
378 the C<warn_obsolete> option set to false:
380 Imager::init(warn_obsolete=>0);
382 At some point in the future these obsolete options will no longer be
385 =head2 PNM (Portable aNy Map)
387 Imager can write PGM (Portable Gray Map) and PPM (Portable PixMaps)
388 files, depending on the number of channels in the image. Currently
389 the images are written in binary formats. Only 1 and 3 channel images
390 can be written, including 1 and 3 channel paletted images.
392 $img->write(file=>'foo.ppm') or die $img->errstr;
394 Imager can read both the ASCII and binary versions of each of the PBM
395 (Portable BitMap), PGM and PPM formats.
397 $img->read(file=>'foo.ppm') or die $img->errstr;
399 PNM does not support the spatial resolution tags.
401 The following tags are set when reading a PNM file:
407 X<pnm_maxval>pnm_maxval - the maxvals number from the PGM/PPM header.
408 Always set to 2 for a PBM file.
412 X<pnm_type>pnm_type - the type number from the PNM header, 1 for ASCII
413 PBM files, 2 for ASCII PGM files, 3 for ASCII PPM files, 4 for binary
414 PBM files, 5 for binary PGM files, 6 for binary PPM files.
418 The following tag is checked when writing an image with more than
425 X<pnm_write_wide_data>pnm_write_wide_data - if this is non-zero then
426 write() can write PGM/PPM files with 16-bits/sample. Some
427 applications, for example GIMP 2.2, and tools can only read
428 8-bit/sample binary PNM files, so Imager will only write a 16-bit
429 image when this tag is non-zero.
435 You can supply a C<jpegquality> parameter (0-100) when writing a JPEG
436 file, which defaults to 75%. If you write an image with an alpha
437 channel to a jpeg file then it will be composited against the
438 background set by the C<i_background> parameter (or tag).
440 $img->write(file=>'foo.jpg', jpegquality=>90) or die $img->errstr;
442 Imager will read a grayscale JPEG as a 1 channel image and a color
443 JPEG as a 3 channel image.
445 $img->read(file=>'foo.jpg') or die $img->errstr;
447 The following tags are set in a JPEG image when read, and can be set
452 =item jpeg_density_unit
454 The value of the density unit field in the JFIF header. This is
455 ignored on writing if the C<i_aspect_only> tag is non-zero.
457 The C<i_xres> and C<i_yres> tags are expressed in pixels per inch no
458 matter the value of this tag, they will be converted to/from the value
459 stored in the JPEG file.
461 =item jpeg_density_unit_name
463 This is set when reading a JPEG file to the name of the unit given by
464 C<jpeg_density_unit>. Possible results include C<inch>,
465 C<centimeter>, C<none> (the C<i_aspect_only> tag is also set reading
466 these files). If the value of jpeg_density_unit is unknown then this
475 JPEG supports the spatial resolution tags C<i_xres>, C<i_yres> and
478 If an APP1 block containing EXIF information is found, then any of the
479 following tags can be set:
483 exif_aperture exif_artist exif_brightness exif_color_space
484 exif_contrast exif_copyright exif_custom_rendered exif_date_time
485 exif_date_time_digitized exif_date_time_original
486 exif_digital_zoom_ratio exif_exposure_bias exif_exposure_index
487 exif_exposure_mode exif_exposure_program exif_exposure_time
488 exif_f_number exif_flash exif_flash_energy exif_flashpix_version
489 exif_focal_length exif_focal_length_in_35mm_film
490 exif_focal_plane_resolution_unit exif_focal_plane_x_resolution
491 exif_focal_plane_y_resolution exif_gain_control exif_image_description
492 exif_image_unique_id exif_iso_speed_rating exif_make exif_max_aperture
493 exif_metering_mode exif_model exif_orientation exif_related_sound_file
494 exif_resolution_unit exif_saturation exif_scene_capture_type
495 exif_sensing_method exif_sharpness exif_shutter_speed exif_software
496 exif_spectral_sensitivity exif_sub_sec_time
497 exif_sub_sec_time_digitized exif_sub_sec_time_original
498 exif_subject_distance exif_subject_distance_range
499 exif_subject_location exif_tag_light_source exif_user_comment
500 exif_version exif_white_balance exif_x_resolution exif_y_resolution
504 The following derived tags can also be set:
508 exif_color_space_name exif_contrast_name exif_custom_rendered_name
509 exif_exposure_mode_name exif_exposure_program_name exif_flash_name
510 exif_focal_plane_resolution_unit_name exif_gain_control_name
511 exif_light_source_name exif_metering_mode_name
512 exif_resolution_unit_name exif_saturation_name
513 exif_scene_capture_type_name exif_sensing_method_name
514 exif_sharpness_name exif_subject_distance_range_name
515 exif_white_balance_name
519 The derived tags are for enumerated fields, when the value for the
520 base field is valid then the text that appears in the EXIF
521 specification for that value appears in the derived field. So for
522 example if C<exf_metering_mode> is C<5> then
523 C<exif_metering_mode_name> is set to C<Pattern>.
527 my $image = Imager->new;
528 $image->read(file => 'exiftest.jpg')
529 or die "Cannot load image: ", $image->errstr;
530 print $image->tags(name => "exif_image_description"), "\n";
531 print $image->tags(name => "exif_exposure_mode"), "\n";
532 print $image->tags(name => "exif_exposure_mode_name"), "\n";
534 # for the exiftest.jpg in the Imager distribution the output would be:
535 Imager Development Notes
543 Historically, Imager saves IPTC data when reading a JPEG image, the
544 parseiptc() method returns a list of key/value pairs resulting from a
545 simple decoding of that data.
547 Any future IPTC data decoding is likely to go into tags.
551 =head2 GIF (Graphics Interchange Format)
553 When writing one of more GIF images you can use the same
554 L<Quantization Options|Imager::ImageTypes> as you can when converting
555 an RGB image into a paletted image.
557 When reading a GIF all of the sub-images are combined using the screen
558 size and image positions into one big image, producing an RGB image.
559 This may change in the future to produce a paletted image where possible.
561 When you read a single GIF with C<$img-E<gt>read()> you can supply a
562 reference to a scalar in the C<colors> parameter, if the image is read
563 the scalar will be filled with a reference to an anonymous array of
564 L<Imager::Color> objects, representing the palette of the image. This
565 will be the first palette found in the image. If you want the
566 palettes for each of the images in the file, use C<read_multi()> and
567 use the C<getcolors()> method on each image.
569 GIF does not support the spatial resolution tags.
571 Imager will set the following tags in each image when reading, and can
572 use most of them when writing to GIF:
578 gif_left - the offset of the image from the left of the "screen"
579 ("Image Left Position")
583 gif_top - the offset of the image from the top of the "screen" ("Image
588 gif_interlace - non-zero if the image was interlaced ("Interlace
593 gif_screen_width, gif_screen_height - the size of the logical
594 screen. When writing this is used as the minimum. If any image being
595 written would extend beyond this then the screen size is extended.
596 ("Logical Screen Width", "Logical Screen Height").
600 gif_local_map - Non-zero if this image had a local color map. If set
601 for an image when writing the image is quantized separately from the
602 other images in the file.
606 gif_background - The index in the global colormap of the logical
607 screen's background color. This is only set if the current image uses
608 the global colormap. You can set this on write too, but for it to
609 choose the color you want, you will need to supply only paletted
610 images and set the C<gif_eliminate_unused> tag to 0.
614 gif_trans_index - The index of the color in the colormap used for
615 transparency. If the image has a transparency then it is returned as
616 a 4 channel image with the alpha set to zero in this palette entry.
617 This value is not used when writing. ("Transparent Color Index")
621 gif_trans_color - A reference to an Imager::Color object, which is the
622 colour to use for the palette entry used to represent transparency in
623 the palette. You need to set the transp option (see L<Quantization
624 options>) for this value to be used.
628 gif_delay - The delay until the next frame is displayed, in 1/100 of a
629 second. ("Delay Time").
633 gif_user_input - whether or not a user input is expected before
634 continuing (view dependent) ("User Input Flag").
638 gif_disposal - how the next frame is displayed ("Disposal Method")
642 gif_loop - the number of loops from the Netscape Loop extension. This
643 may be zero to loop forever.
647 gif_comment - the first block of the first gif comment before each
652 gif_eliminate_unused - If this is true, when you write a paletted
653 image any unused colors will be eliminated from its palette. This is
658 gif_colormap_size - the original size of the color map for the image.
659 The color map of the image may have been expanded to include out of
664 Where applicable, the ("name") is the name of that field from the GIF89
667 The following gif writing options are obsolete, you should set the
668 corresponding tag in the image, either by using the tags functions, or
669 by supplying the tag and value as options.
675 gif_each_palette - Each image in the gif file has it's own palette if
676 this is non-zero. All but the first image has a local colour table
677 (the first uses the global colour table.
679 Use C<gif_local_map> in new code.
683 interlace - The images are written interlaced if this is non-zero.
685 Use C<gif_interlace> in new code.
689 gif_delays - A reference to an array containing the delays between
690 images, in 1/100 seconds.
692 Use C<gif_delay> in new code.
696 gif_positions - A reference to an array of references to arrays which
697 represent screen positions for each image.
699 New code should use the C<gif_left> and C<gif_top> tags.
703 gif_loop_count - If this is non-zero the Netscape loop extension block
704 is generated, which makes the animation of the images repeat.
706 This is currently unimplemented due to some limitations in giflib.
710 You can supply a C<page> parameter to the C<read()> method to read
711 some page other than the first. The page is 0 based:
713 # read the second image in the file
714 $image->read(file=>"example.gif", page=>1)
715 or die "Cannot read second page: ",$image->errstr,"\n";
717 Before release 0.46, Imager would read multi-image GIF image files
718 into a single image, overlaying each of the images onto the virtual
721 As of 0.46 the default is to read the first image from the file, as if
722 called with C<< page => 0 >>.
724 You can return to the previous behaviour by calling read with the
725 C<gif_consolidate> parameter set to a true value:
727 $img->read(file=>$some_gif_file, gif_consolidate=>1);
729 =head2 TIFF (Tagged Image File Format)
731 Imager can write images to either paletted or RGB TIFF images,
732 depending on the type of the source image. Currently if you write a
733 16-bit/sample or double/sample image it will be written as an
734 8-bit/sample image. Only 1 or 3 channel images can be written.
736 If you are creating images for faxing you can set the I<class>
737 parameter set to C<fax>. By default the image is written in fine
738 mode, but this can be overridden by setting the I<fax_fine> parameter
739 to zero. Since a fax image is bi-level, Imager uses a threshold to
740 decide if a given pixel is black or white, based on a single channel.
741 For greyscale images channel 0 is used, for color images channel 1
742 (green) is used. If you want more control over the conversion you can
743 use $img->to_paletted() to product a bi-level image. This way you can
746 my $bilevel = $img->to_paletted(make_colors => 'mono',
747 translate => 'errdiff',
748 errdiff => 'stucki');
754 If set to 'fax' the image will be written as a bi-level fax image.
758 By default when I<class> is set to 'fax' the image is written in fine
759 mode, you can select normal mode by setting I<fax_fine> to 0.
763 Imager should be able to read any TIFF image you supply. Paletted
764 TIFF images are read as paletted Imager images, since paletted TIFF
765 images have 16-bits/sample (48-bits/color) this means the bottom
766 8-bits are lost, but this shouldn't be a big deal. Currently all
767 direct color images are read at 8-bits/sample.
769 TIFF supports the spatial resolution tags. See the
770 C<tiff_resolutionunit> tag for some extra options.
772 As of Imager 0.62 Imager reads:
778 16-bit grey, RGB, or CMYK image, including a possible alpha channel as
779 a 16-bit/sample image.
783 32-bit grey, RGB image, including a possible alpha channel as a
788 bi-level images as paletted images containing only black and white,
789 which other formats will also write as bi-level.
793 tiled paletted images are now handled correctly
797 The following tags are set in a TIFF image when read, and can be set
802 =item tiff_compression
804 When reading an image this is set to the numeric value of the TIFF
807 On writing you can set this to either a numeric compression tag value,
808 or one of the following values:
810 Ident Number Description
811 none 1 No compression
812 packbits 32773 Macintosh RLE
814 fax3 3 CCITT Group 3 fax encoding (T.4)
816 fax4 4 CCITT Group 4 fax encoding (T.6)
820 zip 8 Deflate (GZIP) Non-standard
822 oldzip 32946 Deflate with an older code.
823 ccittrlew 32771 Word aligned CCITT RLE
825 In general a compression setting will be ignored where it doesn't make
826 sense, eg. C<jpeg> will be ignored for compression if the image is
827 being written as bilevel.
829 Imager attempts to check that your build of libtiff supports the given
830 compression, and will fallback to C<packbits> if it isn't enabled.
831 eg. older distributions didn't include LZW compression, and JPEG
832 compression is only available if libtiff is configured with libjpeg's
835 $im->write(file => 'foo.tif', tiff_compression => 'lzw')
838 =item tiff_jpegquality
840 If I<tiff_compression> if C<jpeg> then this can be a number from 1 to
841 100 giving the JPEG compression quality. High values are better
842 quality and larger files.
844 =item tiff_resolutionunit
846 The value of the ResolutionUnit tag. This is ignored on writing if
847 the i_aspect_only tag is non-zero.
849 The C<i_xres> and C<i_yres> tags are expressed in pixels per inch no
850 matter the value of this tag, they will be converted to/from the value
851 stored in the TIFF file.
853 =item tiff_resolutionunit_name
855 This is set when reading a TIFF file to the name of the unit given by
856 C<tiff_resolutionunit>. Possible results include C<inch>,
857 C<centimeter>, C<none> (the C<i_aspect_only> tag is also set reading
858 these files) or C<unknown>.
860 =item tiff_bitspersample
862 Bits per sample from the image. This value is not used when writing
863 an image, it is only set on a read image.
865 =item tiff_photometric
867 Value of the PhotometricInterpretation tag from the image. This value
868 is not used when writing an image, it is only set on a read image.
870 =item tiff_documentname
872 =item tiff_imagedescription
886 =item tiff_hostcomputer
888 Various strings describing the image. tiff_datetime must be formatted
889 as "YYYY:MM:DD HH:MM:SS". These correspond directly to the mixed case
890 names in the TIFF specification. These are set in images read from a
891 TIFF and saved when writing a TIFF image.
895 You can supply a C<page> parameter to the C<read()> method to read
896 some page other than the first. The page is 0 based:
898 # read the second image in the file
899 $image->read(file=>"example.tif", page=>1)
900 or die "Cannot read second page: ",$image->errstr,"\n";
902 Note: Imager uses the TIFF*RGBA* family of libtiff functions,
903 unfortunately these don't support alpha channels on CMYK images. This
904 will result in a full coverage alpha channel on CMYK images with an
905 alpha channel, until this is implemented in libtiff (or Imager's TIFF
906 implementation changes.)
908 If you read an image with multiple alpha channels, then only the first
909 alpha channel will be read.
911 Currently Imager's TIFF support reads all direct color images as 8-bit
912 RGB images, this may change in the future to reading 16-bit/sample
915 Currently tags that control the output color type and compression are
916 ignored when writing, this may change in the future. If you have
917 processes that rely upon Imager always producing packbits compressed
918 RGB images, you should strip any tags before writing.
922 Imager can write 24-bit RGB, and 8, 4 and 1-bit per pixel paletted
923 Windows BMP files. Currently you cannot write compressed BMP files
926 Imager can read 24-bit RGB, and 8, 4 and 1-bit perl pixel paletted
927 Windows BMP files. There is some support for reading 16-bit per pixel
928 images, but I haven't found any for testing.
930 BMP has no support for multi-image files.
932 BMP files support the spatial resolution tags, but since BMP has no
933 support for storing only an aspect ratio, if C<i_aspect_only> is set
934 when you write the C<i_xres> and C<i_yres> values are scaled so the
937 The following tags are set when you read an image from a BMP file:
941 =item bmp_compression
943 The type of compression, if any. This can be any of the following
954 8-bits/pixel paletted value RLE compression.
958 4-bits/pixel paletted value RLE compression.
960 =item BI_BITFIELDS (3)
966 =item bmp_compression_name
968 The bmp_compression value as a BI_* string
970 =item bmp_important_colors
972 The number of important colors as defined by the writer of the image.
974 =item bmp_used_colors
976 Number of color used from the BMP header
980 The file size from the BMP header
984 Number of bits stored per pixel. (24, 8, 4 or 1)
990 When storing targa images rle compression can be activated with the
991 'compress' parameter, the 'idstring' parameter can be used to set the
992 targa comment field and the 'wierdpack' option can be used to use the
993 15 and 16 bit targa formats for rgb and rgba data. The 15 bit format
994 has 5 of each red, green and blue. The 16 bit format in addition
995 allows 1 bit of alpha. The most significant bits are used for each
1013 When reading raw images you need to supply the width and height of the
1014 image in the xsize and ysize options:
1016 $img->read(file=>'foo.raw', xsize=>100, ysize=>100)
1017 or die "Cannot read raw image\n";
1019 If your input file has more channels than you want, or (as is common),
1020 junk in the fourth channel, you can use the datachannels and
1021 storechannels options to control the number of channels in your input
1022 file and the resulting channels in your image. For example, if your
1023 input image uses 32-bits per pixel with red, green, blue and junk
1024 values for each pixel you could do:
1026 $img->read(file=>'foo.raw', xsize=>100, ysize=>100, datachannels=>4,
1028 or die "Cannot read raw image\n";
1030 Normally the raw image is expected to have the value for channel 1
1031 immediately following channel 0 and channel 2 immediately following
1032 channel 1 for each pixel. If your input image has all the channel 0
1033 values for the first line of the image, followed by all the channel 1
1034 values for the first line and so on, you can use the interleave option:
1036 $img->read(file=>'foo.raw', xsize=100, ysize=>100, interleave=>1)
1037 or die "Cannot read raw image\n";
1041 There are no PNG specific tags.
1043 =head2 ICO (Microsoft Windows Icon) and CUR (Microsoft Windows Cursor)
1045 Icon and Cursor files are very similar, the only differences being a
1046 number in the header and the storage of the cursor hotspot. I've
1047 treated them separately so that you're not messing with tags to
1048 distinguish between them.
1050 The following tags are set when reading an icon image and are used
1057 This is the AND mask of the icon. When used as an icon in Windows 1
1058 bits in the mask correspond to pixels that are modified by the source
1059 image rather than simply replaced by the source image.
1061 Rather than requiring a binary bitmap this is accepted in a specific format:
1067 first line consisting of the 0 placeholder, the 1 placeholder and a
1072 following lines which contain 0 and 1 placeholders for each scanline
1073 of the image, starting from the top of the image.
1077 When reading an image, '.' is used as the 0 placeholder and '*' as the
1078 1 placeholder. An example:
1081 ..........................******
1082 ..........................******
1083 ..........................******
1084 ..........................******
1085 ...........................*****
1086 ............................****
1087 ............................****
1088 .............................***
1089 .............................***
1090 .............................***
1091 .............................***
1092 ..............................**
1093 ..............................**
1094 ...............................*
1095 ...............................*
1096 ................................
1097 ................................
1098 ................................
1099 ................................
1100 ................................
1101 ................................
1102 *...............................
1103 **..............................
1104 **..............................
1105 ***.............................
1106 ***.............................
1107 ****............................
1108 ****............................
1109 *****...........................
1110 *****...........................
1111 *****...........................
1112 *****...........................
1116 The following tags are set when reading an icon:
1122 The number of bits per pixel used to store the image.
1126 For cursor files the following tags are set and read when reading and
1133 This is the same as the ico_mask above.
1139 The "hot" spot of the cursor image. This is the spot on the cursor
1140 that you click with. If you set these to out of range values they are
1141 clipped to the size of the image when written to the file.
1145 The following parameters can be supplied to read() or read_multi() to
1146 control reading of ICO/CUR files:
1152 ico_masked - if true, the default, then the icon/cursors mask is
1153 applied as an alpha channel to the image. This may result in a
1154 paletted image being returned as a direct color image. Default: 1
1156 # retrieve the image as stored, without using the mask as an alpha
1158 $img->read(file => 'foo.ico', ico_masked => 0)
1159 or die $img->errstr;
1161 This was introduced in Imager 0.60. Previously reading ICO images
1162 acted as if C<<ico_masked => 0>>.
1166 C<cur_bits> is set when reading a cursor.
1170 my $img = Imager->new(xsize => 32, ysize => 32, channels => 4);
1171 $im->box(color => 'FF0000');
1172 $im->write(file => 'box.ico');
1174 $im->settag(name => 'cur_hotspotx', value => 16);
1175 $im->settag(name => 'cur_hotspoty', value => 16);
1176 $im->write(file => 'box.cur');
1178 =head2 SGI (RGB, BW)
1180 SGI images, often called by the extensions, RGB or BW, can be stored
1181 either uncompressed or compressed using an RLE compression.
1183 By default, when saving to an extension of C<rgb>, C<bw>, C<sgi>,
1184 C<rgba> the file will be saved in SGI format. The file extension is
1185 otherwise ignored, so saving a 3-channel image to a C<.bw> file will
1186 result in a 3-channel image on disk.
1188 The following tags are set when reading a SGI image:
1194 i_comment - the IMAGENAME field from the image. Also written to the
1199 sgi_pixmin, sgi_pixmax - the PIXMIN and PIXMAX fields from the image.
1200 On reading image data is expanded from this range to the full range of
1201 samples in the image.
1205 sgi_bpc - the number of bytes per sample for the image. Ignored when
1210 sgi_rle - whether or not the image is compressed. If this is non-zero
1211 when writing the image will be compressed.
1215 =head1 ADDING NEW FORMATS
1217 To support a new format for reading, call the register_reader() class
1222 =item register_reader
1224 Registers single or multiple image read functions.
1232 type - the identifier of the file format, if Imager's
1233 i_test_format_probe() can identify the format then this value should
1234 match i_test_format_probe()'s result.
1236 This parameter is required.
1240 single - a code ref to read a single image from a file. This is
1247 the object that read() was called on,
1251 an Imager::IO object that should be used to read the file, and
1255 all the parameters supplied to the read() method.
1259 The single parameter is required.
1263 multiple - a code ref which is called to read multiple images from a
1264 file. This is supplied:
1270 an Imager::IO object that should be used to read the file, and
1274 all the parameters supplied to the read_multi() method.
1282 # from Imager::File::ICO
1283 Imager->register_reader
1288 my ($im, $io, %hsh) = @_;
1289 $im->{IMG} = i_readico_single($io, $hsh{page} || 0);
1291 unless ($im->{IMG}) {
1292 $im->_set_error(Imager->_error_as_msg);
1299 my ($io, %hsh) = @_;
1301 my @imgs = i_readico_multi($io);
1303 Imager->_set_error(Imager->_error_as_msg);
1307 bless { IMG => $_, DEBUG => $Imager::DEBUG, ERRSTR => undef }, 'Imager'
1312 =item register_writer
1314 Registers single or multiple image write functions.
1322 type - the identifier of the file format. This is typically the
1323 extension in lowercase.
1325 This parameter is required.
1329 single - a code ref to write a single image to a file. This is
1336 the object that write() was called on,
1340 an Imager::IO object that should be used to write the file, and
1344 all the parameters supplied to the write() method.
1348 The single parameter is required.
1352 multiple - a code ref which is called to write multiple images to a
1353 file. This is supplied:
1359 the class name write_multi() was called on, this is typically
1364 an Imager::IO object that should be used to write the file, and
1368 all the parameters supplied to the read_multi() method.
1376 If you name the reader module C<Imager::File::>I<your-format-name>
1377 where I<your-format-name> is a fully upper case version of the type
1378 value you would pass to read(), read_multi(), write() or write_multi()
1379 then Imager will attempt to load that module if it has no other way to
1380 read or write that format.
1382 For example, if you create a module Imager::File::GIF and the user has
1383 built Imager without it's normal GIF support then an attempt to read a
1384 GIF image will attempt to load Imager::File::GIF.
1386 If your module can only handle reading then you can name your module
1387 C<Imager::File::>I<your-format-name>C<Reader> and Imager will attempt
1390 If your module can only handle writing then you can name your module
1391 C<Imager::File::>I<your-format-name>C<Writer> and Imager will attempt
1396 =head2 Producing an image from a CGI script
1398 Once you have an image the basic mechanism is:
1404 set STDOUT to autoflush
1408 output a content-type header, and optionally a content-length header
1412 put STDOUT into binmode
1416 call write() with the C<fd> or C<fh> parameter. You will need to
1417 provide the C<type> parameter since Imager can't use the extension to
1418 guess the file format you want.
1422 # write an image from a CGI script
1424 use CGI qw(:standard);
1427 print header(-type=>'image/gif');
1428 $img->write(type=>'gif', fd=>fileno(STDOUT))
1429 or die $img->errstr;
1431 If you want to send a content length you can send the output to a
1432 scalar to get the length:
1435 $img->write(type=>'gif', data=>\$data)
1436 or die $img->errstr;
1438 print header(-type=>'image/gif', -content_length=>length($data));
1441 =head2 Writing an animated GIF
1443 The basic idea is simple, just use write_multi():
1446 Imager->write_multi({ file=>$filename, type=>'gif' }, @imgs);
1448 If your images are RGB images the default quantization mechanism will
1449 produce a very good result, but can take a long time to execute. You
1450 could either use the standard webmap:
1452 Imager->write_multi({ file=>$filename,
1454 make_colors=>'webmap' },
1457 or use a median cut algorithm to built a fairly optimal color map:
1459 Imager->write_multi({ file=>$filename,
1461 make_colors=>'mediancut' },
1464 By default all of the images will use the same global colormap, which
1465 will produce a smaller image. If your images have significant color
1466 differences, you may want to generate a new palette for each image:
1468 Imager->write_multi({ file=>$filename,
1470 make_colors=>'mediancut',
1471 gif_local_map => 1 },
1474 which will set the C<gif_local_map> tag in each image to 1.
1475 Alternatively, if you know only some images have different colors, you
1476 can set the tag just for those images:
1478 $imgs[2]->settag(name=>'gif_local_map', value=>1);
1479 $imgs[4]->settag(name=>'gif_local_map', value=>1);
1481 and call write_multi() without a C<gif_local_map> parameter, or supply
1482 an arrayref of values for the tag:
1484 Imager->write_multi({ file=>$filename,
1486 make_colors=>'mediancut',
1487 gif_local_map => [ 0, 0, 1, 0, 1 ] },
1490 Other useful parameters include C<gif_delay> to control the delay
1491 between frames and C<transp> to control transparency.
1493 =head2 Reading tags after reading an image
1495 This is pretty simple:
1497 # print the author of a TIFF, if any
1498 my $img = Imager->new;
1499 $img->read(file=>$filename, type='tiff') or die $img->errstr;
1500 my $author = $img->tags(name=>'tiff_author');
1501 if (defined $author) {
1502 print "Author: $author\n";
1507 When saving Gif images the program does NOT try to shave of extra
1508 colors if it is possible. If you specify 128 colors and there are
1509 only 2 colors used - it will have a 128 colortable anyway.