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)
25 You can read and write a variety of images formats, assuming you have
26 the appropriate libraries, and images can be read or written to/from
27 files, file handles, file descriptors, scalars, or through callbacks.
29 To see which image formats Imager is compiled to support the following
30 code snippet is sufficient:
33 print join " ", keys %Imager::formats;
35 This will include some other information identifying libraries rather
42 Reading writing to and from files is simple, use the C<read()>
43 method to read an image:
45 my $img = Imager->new;
46 $img->read(file=>$filename, type=>$type)
47 or die "Cannot read $filename: ", $img->errstr;
51 and the C<write()> method to write an image:
53 $img->write(file=>$filename, type=>$type)
54 or die "Cannot write $filename: ", $img->errstr;
58 If you're reading from a format that supports multiple images per
59 file, use the C<read_multi()> method:
61 my @imgs = Imager->read_multi(file=>$filename, type=>$type)
62 or die "Cannot read $filename: ", Imager->errstr;
66 and if you want to write multiple images to a single file use the
67 C<write_multi()> method:
69 Imager->write_multi({ file=> $filename, type=>$type }, @images)
70 or die "Cannot write $filename: ", Imager->errstr;
74 If the I<filename> includes an extension that Imager recognizes, then
75 you don't need the I<type>, but you may want to provide one anyway.
76 See L</Guessing types> for information on controlling this
79 The C<type> parameter is a lowercase representation of the file type,
80 and can be any of the following:
82 bmp Windows BitMaP (BMP)
83 gif Graphics Interchange Format (GIF)
85 png Portable Network Graphics (PNG)
86 pnm Portable aNyMap (PNM)
90 tiff Tagged Image File Format (TIFF)
92 When you read an image, Imager may set some tags, possibly including
93 information about the spatial resolution, textual information, and
94 animation information. See L<Imager::ImageTypes/Tags> for specifics.
96 The open() method is a historical alias for the read() method.
98 =head2 Input and output
100 When reading or writing you can specify one of a variety of sources or
107 The C<file> parameter is the name of the image file to be written to
108 or read from. If Imager recognizes the extension of the file you do
109 not need to supply a C<type>.
111 # write in tiff format
112 $image->write(file => "example.tif")
113 or die $image->errstr;
115 $image->write(file => 'foo.tmp', type => 'tiff')
116 or die $image->errstr;
118 my $image = Imager->new;
119 $image->read(file => 'example.tif')
120 or die $image->errstr;
124 C<fh> is a file handle, typically either returned from
125 C<<IO::File->new()>>, or a glob from an C<open> call. You should call
126 C<binmode> on the handle before passing it to Imager.
128 Imager will set the handle to autoflush to make sure any buffered data
129 is flushed , since Imager will write to the file descriptor (from
130 fileno()) rather than writing at the perl level.
132 $image->write(fh => \*STDOUT, type => 'gif')
133 or die $image->errstr;
135 # for example, a file uploaded via CGI.pm
136 $image->read(fd => $cgi->param('file'))
137 or die $image->errstr;
141 C<fd> is a file descriptor. You can get this by calling the
142 C<fileno()> function on a file handle, or by using one of the standard
143 file descriptor numbers.
145 If you get this from a perl file handle, you may need to flush any
146 buffered output, otherwise it may appear in the output stream after
149 $image->write(fd => file(STDOUT), type => 'gif')
150 or die $image->errstr;
154 When reading data, C<data> is a scalar containing the image file data,
155 when writing, C<data> is a reference to the scalar to save the image
156 file data too. For GIF images you will need giflib 4 or higher, and
157 you may need to patch giflib to use this option for writing.
160 $image->write(data => \$data, type => 'tiff')
161 or die $image->errstr;
163 my $data = $row->{someblob}; # eg. from a database
164 $image->read(data => $data)
165 or die $image->errstr;
169 Imager will make calls back to your supplied coderefs to read, write
170 and seek from/to/through the image file.
172 When reading from a file you can use either C<callback> or C<readcb>
173 to supply the read callback, and when writing C<callback> or
174 C<writecb> to supply the write callback.
176 When writing you can also supply the C<maxbuffer> option to set the
177 maximum amount of data that will be buffered before your write
178 callback is called. Note: the amount of data supplied to your
179 callback can be smaller or larger than this size.
181 The read callback is called with 2 parameters, the minimum amount of
182 data required, and the maximum amount that Imager will store in it's C
183 level buffer. You may want to return the minimum if you have a slow
184 data source, or the maximum if you have a fast source and want to
185 prevent many calls to your perl callback. The read data should be
186 returned as a scalar.
188 Your write callback takes exactly one parameter, a scalar containing
189 the data to be written. Return true for success.
191 The seek callback takes 2 parameters, a I<POSITION>, and a I<WHENCE>,
192 defined in the same way as perl's seek function.
194 You can also supply a C<closecb> which is called with no parameters
195 when there is no more data to be written. This could be used to flush
201 $data .= unpack("H*", shift);
204 $image->write(callback => \&mywrite, type => 'gif')
205 or die $image->errstr;
207 Note that for reading you'll almost always need to provide a
212 =head2 Guessing types
214 When writing to a file, if you don't supply a C<type> parameter Imager
215 will attempt to guess it from the filename. This is done by calling
216 the code reference stored in C<$Imager::FORMATGUESS>. This is only
217 done when write() or write_multi() is called with a C<file> parameter.
219 The default function value of C<$Imager::FORMATGUESS> is
220 C<\&Imager::def_guess_type>.
226 This is the default function Imager uses to derive a file type from a
227 file name. This is a function, not a method.
229 Accepts a single parameter, the filename and returns the type or
234 You can replace function with your own implementation if you have some
235 specialized need. The function takes a single parameter, the name of
236 the file, and should return either a file type or under.
238 # I'm writing jpegs to weird filenames
239 local $Imager::FORMATGUESS = sub { 'jpeg' };
241 When reading a file Imager examines beginning of the file for
242 identifying information. The current implementation attempts to
243 detect the following image types beyond those supported by Imager:
247 xpm, mng, jng, SGI RGB, ilbm, pcx, fits, psd (Photoshop), eps, Utah
252 =head2 Limiting the sizes of images you read
256 =item set_file_limits
258 In some cases you will be receiving images from an untested source,
259 such as submissions via CGI. To prevent such images from consuming
260 large amounts of memory, you can set limits on the dimensions of
261 images you read from files:
267 width - limit the width in pixels of the image
271 height - limit the height in pixels of the image
275 bytes - limits the amount of storage used by the image. This depends
276 on the width, height, channels and sample size of the image. For
277 paletted images this is calculated as if the image was expanded to a
282 To set the limits, call the class method set_file_limits:
284 Imager->set_file_limits(width=>$max_width, height=>$max_height);
286 You can pass any or all of the limits above, any limits you do not
287 pass are left as they were.
289 Any limit of zero is treated as unlimited.
291 By default, all of the limits are zero, or unlimited.
293 You can reset all of the limited to their defaults by passing in the
294 reset parameter as a true value:
297 Imager->set_file_limits(reset=>1);
299 This can be used with the other limits to reset all but the limit you
302 # only width is limited
303 Imager->set_file_limits(reset=>1, width=>100);
305 # only bytes is limited
306 Imager->set_file_limits(reset=>1, bytes=>10_000_000);
308 =item get_file_limits
310 You can get the current limits with the get_file_limits() method:
312 my ($max_width, $max_height, $max_bytes) =
313 Imager->get_file_limits();
317 =head1 TYPE SPECIFIC INFORMATION
319 The different image formats can write different image type, and some have
320 different options to control how the images are written.
322 When you call C<write()> or C<write_multi()> with an option that has
323 the same name as a tag for the image format you're writing, then the
324 value supplied to that option will be used to set the corresponding
325 tag in the image. Depending on the image format, these values will be
326 used when writing the image.
328 This replaces the previous options that were used when writing GIF
329 images. Currently if you use an obsolete option, it will be converted
330 to the equivalent tag and Imager will produced a warning. You can
331 suppress these warnings by calling the C<Imager::init()> function with
332 the C<warn_obsolete> option set to false:
334 Imager::init(warn_obsolete=>0);
336 At some point in the future these obsolete options will no longer be
339 =head2 PNM (Portable aNy Map)
341 Imager can write PGM (Portable Gray Map) and PPM (Portable PixMaps)
342 files, depending on the number of channels in the image. Currently
343 the images are written in binary formats. Only 1 and 3 channel images
344 can be written, including 1 and 3 channel paletted images.
346 $img->write(file=>'foo.ppm') or die $img->errstr;
348 Imager can read both the ASCII and binary versions of each of the PBM
349 (Portable BitMap), PGM and PPM formats.
351 $img->read(file=>'foo.ppm') or die $img->errstr;
353 PNM does not support the spatial resolution tags.
357 You can supply a C<jpegquality> parameter (0-100) when writing a JPEG
358 file, which defaults to 75%. Only 1 and 3 channel images
359 can be written, including 1 and 3 channel paletted images.
361 $img->write(file=>'foo.jpg', jpegquality=>90) or die $img->errstr;
363 Imager will read a grayscale JPEG as a 1 channel image and a color
364 JPEG as a 3 channel image.
366 $img->read(file=>'foo.jpg') or die $img->errstr;
368 The following tags are set in a JPEG image when read, and can be set
373 =item jpeg_density_unit
375 The value of the density unit field in the JFIF header. This is
376 ignored on writing if the i_aspect_only tag is non-zero.
378 The C<i_xres> and C<i_yres> tags are expressed in pixels per inch no
379 matter the value of this tag, they will be converted to/from the value
380 stored in the JPEG file.
382 =item jpeg_density_unit_name
384 This is set when reading a JPEG file to the name of the unit given by
385 C<jpeg_density_unit>. Possible results include C<inch>,
386 C<centimeter>, C<none> (the C<i_aspect_only> tag is also set reading
387 these files). If the value of jpeg_density_unit is unknown then this
396 JPEG supports the spatial resolution tags C<i_xres>, C<i_yres> and
399 If an APP1 block containing EXIF information is found, then any of the
400 following tags can be set:
404 exif_aperture exif_artist exif_brightness exif_color_space
405 exif_contrast exif_copyright exif_custom_rendered exif_date_time
406 exif_date_time_digitized exif_date_time_original
407 exif_digital_zoom_ratio exif_exposure_bias exif_exposure_index
408 exif_exposure_mode exif_exposure_program exif_exposure_time
409 exif_f_number exif_flash exif_flash_energy exif_flashpix_version
410 exif_focal_length exif_focal_length_in_35mm_film
411 exif_focal_plane_resolution_unit exif_focal_plane_x_resolution
412 exif_focal_plane_y_resolution exif_gain_control exif_image_description
413 exif_image_unique_id exif_iso_speed_rating exif_make exif_max_aperture
414 exif_metering_mode exif_model exif_orientation exif_related_sound_file
415 exif_resolution_unit exif_saturation exif_scene_capture_type
416 exif_sensing_method exif_sharpness exif_shutter_speed exif_software
417 exif_spectral_sensitivity exif_sub_sec_time
418 exif_sub_sec_time_digitized exif_sub_sec_time_original
419 exif_subject_distance exif_subject_distance_range
420 exif_subject_location exif_tag_light_source exif_user_comment
421 exif_version exif_white_balance exif_x_resolution exif_y_resolution
425 The following derived tags can also be set:
429 exif_color_space_name exif_contrast_name exif_custom_rendered_name
430 exif_exposure_mode_name exif_exposure_program_name exif_flash_name
431 exif_focal_plane_resolution_unit_name exif_gain_control_name
432 exif_light_source_name exif_metering_mode_name
433 exif_resolution_unit_name exif_saturation_name
434 exif_scene_capture_type_name exif_sensing_method_name
435 exif_sharpness_name exif_subject_distance_range_name
436 exif_white_balance_name
440 The derived tags are for enumerated fields, when the value for the
441 base field is valid then the text that appears in the EXIF
442 specification for that value appears in the derived field. So for
443 example if C<exf_metering_mode> is C<5> then
444 C<exif_metering_mode_name> is set to C<Pattern>.
450 Historically, Imager saves IPTC data when reading a JPEG image, the
451 parseiptc() method returns a list of key/value pairs resulting from a
452 simple decoding of that data.
454 Any future IPTC data decoding is likely to go into tags.
458 =head2 GIF (Graphics Interchange Format)
460 When writing one of more GIF images you can use the same
461 L<Quantization Options|Imager::ImageTypes> as you can when converting
462 an RGB image into a paletted image.
464 When reading a GIF all of the sub-images are combined using the screen
465 size and image positions into one big image, producing an RGB image.
466 This may change in the future to produce a paletted image where possible.
468 When you read a single GIF with C<$img-E<gt>read()> you can supply a
469 reference to a scalar in the C<colors> parameter, if the image is read
470 the scalar will be filled with a reference to an anonymous array of
471 L<Imager::Color> objects, representing the palette of the image. This
472 will be the first palette found in the image. If you want the
473 palettes for each of the images in the file, use C<read_multi()> and
474 use the C<getcolors()> method on each image.
476 GIF does not support the spatial resolution tags.
478 Imager will set the following tags in each image when reading, and can
479 use most of them when writing to GIF:
485 the offset of the image from the left of the "screen" ("Image Left
490 the offset of the image from the top of the "screen" ("Image Top Position")
494 non-zero if the image was interlaced ("Interlace Flag")
496 =item gif_screen_width
498 =item gif_screen_height
500 the size of the logical screen. When writing this is used as the
501 minimum. If any image being written would extend beyond this the
502 screen size is extended. ("Logical Screen Width", "Logical Screen
505 When writing this is used as a minimum, if the combination of the
506 image size and the image's C<gif_left> and C<gif_top> is beyond this
507 size then the screen size will be expanded.
511 Non-zero if this image had a local color map. If set for an image
512 when writing the image is quantized separately from the other images
517 The index in the global colormap of the logical screen's background
518 color. This is only set if the current image uses the global
519 colormap. You can set this on write too, but for it to choose the
520 color you want, you will need to supply only paletted images and set
521 the C<gif_eliminate_unused> tag to 0.
523 =item gif_trans_index
525 The index of the color in the colormap used for transparency. If the
526 image has a transparency then it is returned as a 4 channel image with
527 the alpha set to zero in this palette entry. This value is not used
528 when writing. ("Transparent Color Index")
530 =item gif_trans_color
532 A reference to an Imager::Color object, which is the colour to use for
533 the palette entry used to represent transparency in the palette. You
534 need to set the transp option (see L<Quantization options>) for this
539 The delay until the next frame is displayed, in 1/100 of a second.
544 whether or not a user input is expected before continuing (view dependent)
549 how the next frame is displayed ("Disposal Method")
553 the number of loops from the Netscape Loop extension. This may be zero.
557 the first block of the first gif comment before each image.
559 =item gif_eliminate_unused
561 If this is true, when you write a paletted image any unused colors
562 will be eliminated from its palette. This is set by default.
566 Where applicable, the ("name") is the name of that field from the GIF89
569 The following gif writing options are obsolete, you should set the
570 corresponding tag in the image, either by using the tags functions, or
571 by supplying the tag and value as options.
575 =item gif_each_palette
577 Each image in the gif file has it's own palette if this is non-zero.
578 All but the first image has a local colour table (the first uses the
581 Use C<gif_local_map> in new code.
585 The images are written interlaced if this is non-zero.
587 Use C<gif_interlace> in new code.
591 A reference to an array containing the delays between images, in 1/100
594 Use C<gif_delay> in new code.
598 A reference to an array of references to arrays which represent screen
599 positions for each image.
601 New code should use the C<gif_left> and C<gif_top> tags.
605 If this is non-zero the Netscape loop extension block is generated,
606 which makes the animation of the images repeat.
608 This is currently unimplemented due to some limitations in giflib.
612 You can supply a C<page> parameter to the C<read()> method to read
613 some page other than the first. The page is 0 based:
615 # read the second image in the file
616 $image->read(file=>"example.gif", page=>1)
617 or die "Cannot read second page: ",$image->errstr,"\n";
619 Before release 0.46, Imager would read multi-image GIF image files
620 into a single image, overlaying each of the images onto the virtual
623 As of 0.46 the default is to read the first image from the file, as if
624 called with C<< page => 0 >>.
626 You can return to the previous behaviour by calling read with the
627 C<gif_consolidate> parameter set to a true value:
629 $img->read(file=>$some_gif_file, gif_consolidate=>1);
631 =head2 TIFF (Tagged Image File Format)
633 Imager can write images to either paletted or RGB TIFF images,
634 depending on the type of the source image. Currently if you write a
635 16-bit/sample or double/sample image it will be written as an
636 8-bit/sample image. Only 1 or 3 channel images can be written.
638 If you are creating images for faxing you can set the I<class>
639 parameter set to C<fax>. By default the image is written in fine
640 mode, but this can be overridden by setting the I<fax_fine> parameter
641 to zero. Since a fax image is bi-level, Imager uses a threshold to
642 decide if a given pixel is black or white, based on a single channel.
643 For greyscale images channel 0 is used, for color images channel 1
644 (green) is used. If you want more control over the conversion you can
645 use $img->to_paletted() to product a bi-level image. This way you can
648 my $bilevel = $img->to_paletted(colors=>[ NC(0,0,0), NC(255,255,255) ],
649 make_colors => 'none',
650 translate => 'errdiff',
651 errdiff => 'stucki');
657 If set to 'fax' the image will be written as a bi-level fax image.
661 By default when I<class> is set to 'fax' the image is written in fine
662 mode, you can select normal mode by setting I<fax_fine> to 0.
666 Imager should be able to read any TIFF image you supply. Paletted
667 TIFF images are read as paletted Imager images, since paletted TIFF
668 images have 16-bits/sample (48-bits/color) this means the bottom
669 8-bits are lost, but this shouldn't be a big deal. Currently all
670 direct color images are read at 8-bits/sample.
672 TIFF supports the spatial resolution tags. See the
673 C<tiff_resolutionunit> tag for some extra options.
675 The following tags are set in a TIFF image when read, and can be set
680 =item tiff_resolutionunit
682 The value of the ResolutionUnit tag. This is ignored on writing if
683 the i_aspect_only tag is non-zero.
685 The C<i_xres> and C<i_yres> tags are expressed in pixels per inch no
686 matter the value of this tag, they will be converted to/from the value
687 stored in the TIFF file.
689 =item tiff_resolutionunit_name
691 This is set when reading a TIFF file to the name of the unit given by
692 C<tiff_resolutionunit>. Possible results include C<inch>,
693 C<centimeter>, C<none> (the C<i_aspect_only> tag is also set reading
694 these files) or C<unknown>.
696 =item tiff_bitspersample
698 Bits per sample from the image. This value is not used when writing
699 an image, it is only set on a read image.
701 =item tiff_photometric
703 Value of the PhotometricInterpretation tag from the image. This value
704 is not used when writing an image, it is only set on a read image.
706 =item tiff_documentname
708 =item tiff_imagedescription
722 =item tiff_hostcomputer
724 Various strings describing the image. tiff_datetime must be formatted
725 as "YYYY:MM:DD HH:MM:SS". These correspond directly to the mixed case
726 names in the TIFF specification. These are set in images read from a
727 TIFF and saved when writing a TIFF image.
729 You can supply a C<page> parameter to the C<read()> method to read
730 some page other than the first. The page is 0 based:
732 # read the second image in the file
733 $image->read(file=>"example.tif", page=>1)
734 or die "Cannot read second page: ",$image->errstr,"\n";
738 Note: Imager uses the TIFF*RGBA* family of libtiff functions,
739 unfortunately these don't support alpha channels on CMYK images. This
740 will result in a full coverage alpha channel on CMYK images with an
741 alpha channel, until this is implemented in libtiff (or Imager's TIFF
742 implementation changes.)
744 If you read an image with multiple alpha channels, then only the first
745 alpha channel will be read.
747 Currently Imager's TIFF support reads all direct color images as 8-bit
748 RGB images, this may change in the future to reading 16-bit/sample
751 Currently tags that control the output color type and compression are
752 ignored when writing, this may change in the future. If you have
753 processes that rely upon Imager always producing packbits compressed
754 RGB images, you should strip any tags before writing.
758 Imager can write 24-bit RGB, and 8, 4 and 1-bit per pixel paletted
759 Windows BMP files. Currently you cannot write compressed BMP files
762 Imager can read 24-bit RGB, and 8, 4 and 1-bit perl pixel paletted
763 Windows BMP files. There is some support for reading 16-bit per pixel
764 images, but I haven't found any for testing.
766 BMP has no support for multi-image files.
768 BMP files support the spatial resolution tags, but since BMP has no
769 support for storing only an aspect ratio, if C<i_aspect_only> is set
770 when you write the C<i_xres> and C<i_yres> values are scaled so the
773 The following tags are set when you read an image from a BMP file:
777 =item bmp_compression
779 The type of compression, if any. This can be any of the following
790 8-bits/pixel paletted value RLE compression.
794 4-bits/pixel paletted value RLE compression.
796 =item BI_BITFIELDS (3)
802 =item bmp_compression_name
804 The bmp_compression value as a BI_* string
806 =item bmp_important_colors
808 The number of important colors as defined by the writer of the image.
810 =item bmp_used_colors
812 Number of color used from the BMP header
816 The file size from the BMP header
820 Number of bits stored per pixel. (24, 8, 4 or 1)
826 When storing targa images rle compression can be activated with the
827 'compress' parameter, the 'idstring' parameter can be used to set the
828 targa comment field and the 'wierdpack' option can be used to use the
829 15 and 16 bit targa formats for rgb and rgba data. The 15 bit format
830 has 5 of each red, green and blue. The 16 bit format in addition
831 allows 1 bit of alpha. The most significant bits are used for each
849 When reading raw images you need to supply the width and height of the
850 image in the xsize and ysize options:
852 $img->read(file=>'foo.raw', xsize=>100, ysize=>100)
853 or die "Cannot read raw image\n";
855 If your input file has more channels than you want, or (as is common),
856 junk in the fourth channel, you can use the datachannels and
857 storechannels options to control the number of channels in your input
858 file and the resulting channels in your image. For example, if your
859 input image uses 32-bits per pixel with red, green, blue and junk
860 values for each pixel you could do:
862 $img->read(file=>'foo.raw', xsize=>100, ysize=>100, datachannels=>4,
864 or die "Cannot read raw image\n";
866 Normally the raw image is expected to have the value for channel 1
867 immediately following channel 0 and channel 2 immediately following
868 channel 1 for each pixel. If your input image has all the channel 0
869 values for the first line of the image, followed by all the channel 1
870 values for the first line and so on, you can use the interleave option:
872 $img->read(file=>'foo.raw', xsize=100, ysize=>100, interleave=>1)
873 or die "Cannot read raw image\n";
877 There are no PNG specific tags.
879 =head2 ICO (Microsoft Windows Icon) and CUR (Microsoft Windows Cursor)
881 Icon and Cursor files are very similar, the only differences being a
882 number in the header and the storage of the cursor hotspot. I've
883 treated them separately so that you're not messing with tags to
884 distinguish between them.
886 The following tags are set when reading an icon image and are used
893 This is the AND mask of the icon. When used as an icon in Windows 1
894 bits in the mask correspond to pixels that are modified by the source
895 image rather than simply replaced by the source image.
897 Rather than requiring a binary bitmap this is accepted in a specific format:
903 first line consisting of the 0 placeholder, the 1 placeholder and a
908 following lines which contain 0 and 1 placeholders for each scanline
909 of the image, starting from the top of the image.
913 When reading an image, '.' is used as the 0 placeholder and '*' as the
914 1 placeholder. An example:
917 ..........................******
918 ..........................******
919 ..........................******
920 ..........................******
921 ...........................*****
922 ............................****
923 ............................****
924 .............................***
925 .............................***
926 .............................***
927 .............................***
928 ..............................**
929 ..............................**
930 ...............................*
931 ...............................*
932 ................................
933 ................................
934 ................................
935 ................................
936 ................................
937 ................................
938 *...............................
939 **..............................
940 **..............................
941 ***.............................
942 ***.............................
943 ****............................
944 ****............................
945 *****...........................
946 *****...........................
947 *****...........................
948 *****...........................
952 The following tags are set when reading an icon:
958 The number of bits per pixel used to store the image.
962 For cursor files the following tags are set and read when reading and
969 This is the same as the ico_mask above.
975 The "hot" spot of the cursor image. This is the spot on the cursor
976 that you click with. If you set these to out of range values they are
977 clipped to the size of the image when written to the file.
981 C<cur_bits> is set when reading a cursor.
985 my $img = Imager->new(xsize => 32, ysize => 32, channels => 4);
986 $im->box(color => 'FF0000');
987 $im->write(file => 'box.ico');
989 $im->settag(name => 'cur_hotspotx', value => 16);
990 $im->settag(name => 'cur_hotspoty', value => 16);
991 $im->write(file => 'box.cur');
993 =head1 ADDING NEW FORMATS
995 To support a new format for reading, call the register_reader() class
1000 =item register_reader
1002 Registers single or multiple image read functions.
1010 type - the identifier of the file format, if Imager's
1011 i_test_format_probe() can identify the format then this value should
1012 match i_test_format_probe()'s result.
1014 This parameter is required.
1018 single - a code ref to read a single image from a file. This is
1025 the object that read() was called on,
1029 an Imager::IO object that should be used to read the file, and
1033 all the parameters supplied to the read() method.
1037 The single parameter is required.
1041 multiple - a code ref which is called to read multiple images from a
1042 file. This is supplied:
1048 an Imager::IO object that should be used to read the file, and
1052 all the parameters supplied to the read_multi() method.
1060 # from Imager::File::ICO
1061 Imager->register_reader
1066 my ($im, $io, %hsh) = @_;
1067 $im->{IMG} = i_readico_single($io, $hsh{page} || 0);
1069 unless ($im->{IMG}) {
1070 $im->_set_error(Imager->_error_as_msg);
1077 my ($io, %hsh) = @_;
1079 my @imgs = i_readico_multi($io);
1081 Imager->_set_error(Imager->_error_as_msg);
1085 bless { IMG => $_, DEBUG => $Imager::DEBUG, ERRSTR => undef }, 'Imager'
1090 =item register_writer
1092 Registers single or multiple image write functions.
1100 type - the identifier of the file format. This is typically the
1101 extension in lowercase.
1103 This parameter is required.
1107 single - a code ref to write a single image to a file. This is
1114 the object that write() was called on,
1118 an Imager::IO object that should be used to write the file, and
1122 all the parameters supplied to the write() method.
1126 The single parameter is required.
1130 multiple - a code ref which is called to write multiple images to a
1131 file. This is supplied:
1137 the class name write_multi() was called on, this is typically
1142 an Imager::IO object that should be used to write the file, and
1146 all the parameters supplied to the read_multi() method.
1154 If you name the reader module C<Imager::File::>I<your-format-name>
1155 where I<your-format-name> is a fully upper case version of the type
1156 value you would pass to read(), read_multi(), write() or write_multi()
1157 then Imager will attempt to load that module if it has no other way to
1158 read or write that format.
1160 For example, if you create a module Imager::File::GIF and the user has
1161 built Imager without it's normal GIF support then an attempt to read a
1162 GIF image will attempt to load Imager::File::GIF.
1164 If your module can only handle reading then you can name your module
1165 C<Imager::File::>I<your-format-name>C<Reader> and Imager will attempt
1168 If your module can only handle writing then you can name your module
1169 C<Imager::File::>I<your-format-name>C<Writer> and Imager will attempt
1174 =head2 Producing an image from a CGI script
1176 Once you have an image the basic mechanism is:
1182 set STDOUT to autoflush
1186 output a content-type header, and optionally a content-length header
1190 put STDOUT into binmode
1194 call write() with the C<fd> or C<fh> parameter. You will need to
1195 provide the C<type> parameter since Imager can't use the extension to
1196 guess the file format you want.
1200 # write an image from a CGI script
1202 use CGI qw(:standard);
1205 print header(-type=>'image/gif');
1206 $img->write(type=>'gif', fd=>fileno(STDOUT))
1207 or die $img->errstr;
1209 If you want to send a content length you can send the output to a
1210 scalar to get the length:
1213 $img->write(type=>'gif', data=>\$data)
1214 or die $img->errstr;
1216 print header(-type=>'image/gif', -content_length=>length($data));
1219 =head2 Writing an animated GIF
1221 The basic idea is simple, just use write_multi():
1224 Imager->write_multi({ file=>$filename, type=>'gif' }, @imgs);
1226 If your images are RGB images the default quantization mechanism will
1227 produce a very good result, but can take a long time to execute. You
1228 could either use the standard webmap:
1230 Imager->write_multi({ file=>$filename,
1232 make_colors=>'webmap' },
1235 or use a median cut algorithm to built a fairly optimal color map:
1237 Imager->write_multi({ file=>$filename,
1239 make_colors=>'mediancut' },
1242 By default all of the images will use the same global colormap, which
1243 will produce a smaller image. If your images have significant color
1244 differences, you may want to generate a new palette for each image:
1246 Imager->write_multi({ file=>$filename,
1248 make_colors=>'mediancut',
1249 gif_local_map => 1 },
1252 which will set the C<gif_local_map> tag in each image to 1.
1253 Alternatively, if you know only some images have different colors, you
1254 can set the tag just for those images:
1256 $imgs[2]->settag(name=>'gif_local_map', value=>1);
1257 $imgs[4]->settag(name=>'gif_local_map', value=>1);
1259 and call write_multi() without a C<gif_local_map> parameter, or supply
1260 an arrayref of values for the tag:
1262 Imager->write_multi({ file=>$filename,
1264 make_colors=>'mediancut',
1265 gif_local_map => [ 0, 0, 1, 0, 1 ] },
1268 Other useful parameters include C<gif_delay> to control the delay
1269 between frames and C<transp> to control transparency.
1271 =head2 Reading tags after reading an image
1273 This is pretty simple:
1275 # print the author of a TIFF, if any
1276 my $img = Imager->new;
1277 $img->read(file=>$filename, type='tiff') or die $img->errstr;
1278 my $author = $img->tags(name=>'tiff_author');
1279 if (defined $author) {
1280 print "Author: $author\n";
1285 When saving Gif images the program does NOT try to shave of extra
1286 colors if it is possible. If you specify 128 colors and there are
1287 only 2 colors used - it will have a 128 colortable anyway.