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>.
113 C<fh> is a file handle, typically either returned from
114 C<<IO::File->new()>>, or a glob from an C<open> call. You should call
115 C<binmode> on the handle before passing it to Imager.
117 Imager will set the handle to autoflush to make sure any buffered data
118 is flushed , since Imager will write to the file descriptor (from
119 fileno()) rather than writing at the perl level.
123 C<fd> is a file descriptor. You can get this by calling the
124 C<fileno()> function on a file handle, or by using one of the standard
125 file descriptor numbers.
127 If you get this from a perl file handle, you may need to flush any
128 buffered output, otherwise it may appear in the output stream after
133 When reading data, C<data> is a scalar containing the image file data,
134 when writing, C<data> is a reference to the scalar to save the image
135 file data too. For GIF images you will need giflib 4 or higher, and
136 you may need to patch giflib to use this option for writing.
140 Imager will make calls back to your supplied coderefs to read, write
141 and seek from/to/through the image file.
143 When reading from a file you can use either C<callback> or C<readcb>
144 to supply the read callback, and when writing C<callback> or
145 C<writecb> to supply the write callback.
147 When writing you can also supply the C<maxbuffer> option to set the
148 maximum amount of data that will be buffered before your write
149 callback is called. Note: the amount of data supplied to your
150 callback can be smaller or larger than this size.
152 The read callback is called with 2 parameters, the minimum amount of
153 data required, and the maximum amount that Imager will store in it's C
154 level buffer. You may want to return the minimum if you have a slow
155 data source, or the maximum if you have a fast source and want to
156 prevent many calls to your perl callback. The read data should be
157 returned as a scalar.
159 Your write callback takes exactly one parameter, a scalar containing
160 the data to be written. Return true for success.
162 The seek callback takes 2 parameters, a I<POSITION>, and a I<WHENCE>,
163 defined in the same way as perl's seek function.
165 You can also supply a C<closecb> which is called with no parameters
166 when there is no more data to be written. This could be used to flush
171 =head2 Guessing types
173 Imager uses the code reference in $Imager::FORMATGUESS to guess the
174 file type when you don't supply a C<type>. The code reference is
175 called with a single parameter, the filename of the file. The code
176 reference is only called if a C<file> parameter is supplied to the
179 Return either a valid Imager file type, or undef.
181 # I'm writing jpegs to weird filenames
182 local $Imager::FORMATGUESS = sub { 'jpeg' };
184 =head2 Limiting the sizes of images you read
186 In some cases you will be receiving images from an untested source,
187 such as submissions via CGI. To prevent such images from consuming
188 large amounts of memory, you can set limits on the dimensions of
189 images you read from files:
195 width - limit the width in pixels of the image
199 height - limit the height in pixels of the image
203 bytes - limits the amount of storage used by the image. This depends
204 on the width, height, channels and sample size of the image. For
205 paletted images this is calculated as if the image was expanded to a
210 To set the limits, call the class method set_file_limits:
212 Imager->set_file_limits(width=>$max_width, height=>$max_height);
214 You can pass any or all of the limits above, any limits you do not
215 pass are left as they were.
217 Any limit of zero is treated as unlimited.
219 By default, all of the limits are zero, or unlimited.
221 You can reset all of the limited to their defaults by passing in the
222 reset parameter as a true value:
225 Imager->set_file_limits(reset=>1);
227 This can be used with the other limits to reset all but the limit you
230 # only width is limited
231 Imager->set_file_limits(reset=>1, width=>100);
233 # only bytes is limited
234 Imager->set_file_limits(reset=>1, bytes=>10_000_000);
236 You can get the current limits with the get_file_limits() method:
238 my ($max_width, $max_height, $max_bytes) =
239 Imager->get_file_limits();
242 =head1 TYPE SPECIFIC INFORMATION
244 The different image formats can write different image type, and some have
245 different options to control how the images are written.
247 When you call C<write()> or C<write_multi()> with an option that has
248 the same name as a tag for the image format you're writing, then the
249 value supplied to that option will be used to set the corresponding
250 tag in the image. Depending on the image format, these values will be
251 used when writing the image.
253 This replaces the previous options that were used when writing GIF
254 images. Currently if you use an obsolete option, it will be converted
255 to the equivalent tag and Imager will produced a warning. You can
256 suppress these warnings by calling the C<Imager::init()> function with
257 the C<warn_obsolete> option set to false:
259 Imager::init(warn_obsolete=>0);
261 At some point in the future these obsolete options will no longer be
264 =head2 PNM (Portable aNy Map)
266 Imager can write PGM (Portable Gray Map) and PPM (Portable PixMaps)
267 files, depending on the number of channels in the image. Currently
268 the images are written in binary formats. Only 1 and 3 channel images
269 can be written, including 1 and 3 channel paletted images.
271 $img->write(file=>'foo.ppm') or die $img->errstr;
273 Imager can read both the ASCII and binary versions of each of the PBM
274 (Portable BitMap), PGM and PPM formats.
276 $img->read(file=>'foo.ppm') or die $img->errstr;
278 PNM does not support the spatial resolution tags.
282 You can supply a C<jpegquality> parameter (0-100) when writing a JPEG
283 file, which defaults to 75%. Only 1 and 3 channel images
284 can be written, including 1 and 3 channel paletted images.
286 $img->write(file=>'foo.jpg', jpegquality=>90) or die $img->errstr;
288 Imager will read a grayscale JPEG as a 1 channel image and a color
289 JPEG as a 3 channel image.
291 $img->read(file=>'foo.jpg') or die $img->errstr;
293 The following tags are set in a JPEG image when read, and can be set
298 =item jpeg_density_unit
300 The value of the density unit field in the JFIF header. This is
301 ignored on writing if the i_aspect_only tag is non-zero.
303 The C<i_xres> and C<i_yres> tags are expressed in pixels per inch no
304 matter the value of this tag, they will be converted to/from the value
305 stored in the JPEG file.
307 =item jpeg_density_unit_name
309 This is set when reading a JPEG file to the name of the unit given by
310 C<jpeg_density_unit>. Possible results include C<inch>,
311 C<centimeter>, C<none> (the C<i_aspect_only> tag is also set reading
312 these files). If the value of jpeg_density_unit is unknown then this
321 JPEG supports the spatial resolution tags C<i_xres>, C<i_yres> and
324 If an APP1 block containing EXIF information is found, then any of the
325 following tags can be set:
329 exif_aperture exif_artist exif_brightness exif_color_space
330 exif_contrast exif_copyright exif_custom_rendered exif_date_time
331 exif_date_time_digitized exif_date_time_original
332 exif_digital_zoom_ratio exif_exposure_bias exif_exposure_index
333 exif_exposure_mode exif_exposure_program exif_exposure_time
334 exif_f_number exif_flash exif_flash_energy exif_flashpix_version
335 exif_focal_length exif_focal_length_in_35mm_film
336 exif_focal_plane_resolution_unit exif_focal_plane_x_resolution
337 exif_focal_plane_y_resolution exif_gain_control exif_image_description
338 exif_image_unique_id exif_iso_speed_rating exif_make exif_max_aperture
339 exif_metering_mode exif_model exif_orientation exif_related_sound_file
340 exif_resolution_unit exif_saturation exif_scene_capture_type
341 exif_sensing_method exif_sharpness exif_shutter_speed exif_software
342 exif_spectral_sensitivity exif_sub_sec_time
343 exif_sub_sec_time_digitized exif_sub_sec_time_original
344 exif_subject_distance exif_subject_distance_range
345 exif_subject_location exif_tag_light_source exif_user_comment
346 exif_version exif_white_balance exif_x_resolution exif_y_resolution
350 The following derived tags can also be set:
354 exif_color_space_name exif_contrast_name exif_custom_rendered_name
355 exif_exposure_mode_name exif_exposure_program_name exif_flash_name
356 exif_focal_plane_resolution_unit_name exif_gain_control_name
357 exif_light_source_name exif_metering_mode_name
358 exif_resolution_unit_name exif_saturation_name
359 exif_scene_capture_type_name exif_sensing_method_name
360 exif_sharpness_name exif_subject_distance_range_name
361 exif_white_balance_name
365 The derived tags are for enumerated fields, when the value for the
366 base field is valid then the text that appears in the EXIF
367 specification for that value appears in the derived field. So for
368 example if C<exf_metering_mode> is C<5> then
369 C<exif_metering_mode_name> is set to C<Pattern>.
371 =head2 GIF (Graphics Interchange Format)
373 When writing one of more GIF images you can use the same
374 L<Quantization Options|Imager::ImageTypes> as you can when converting
375 an RGB image into a paletted image.
377 When reading a GIF all of the sub-images are combined using the screen
378 size and image positions into one big image, producing an RGB image.
379 This may change in the future to produce a paletted image where possible.
381 When you read a single GIF with C<$img-E<gt>read()> you can supply a
382 reference to a scalar in the C<colors> parameter, if the image is read
383 the scalar will be filled with a reference to an anonymous array of
384 L<Imager::Color> objects, representing the palette of the image. This
385 will be the first palette found in the image. If you want the
386 palettes for each of the images in the file, use C<read_multi()> and
387 use the C<getcolors()> method on each image.
389 GIF does not support the spatial resolution tags.
391 Imager will set the following tags in each image when reading, and can
392 use most of them when writing to GIF:
398 the offset of the image from the left of the "screen" ("Image Left
403 the offset of the image from the top of the "screen" ("Image Top Position")
407 non-zero if the image was interlaced ("Interlace Flag")
409 =item gif_screen_width
411 =item gif_screen_height
413 the size of the logical screen. When writing this is used as the
414 minimum. If any image being written would extend beyond this the
415 screen size is extended. ("Logical Screen Width", "Logical Screen
418 When writing this is used as a minimum, if the combination of the
419 image size and the image's C<gif_left> and C<gif_top> is beyond this
420 size then the screen size will be expanded.
424 Non-zero if this image had a local color map. If set for an image
425 when writing the image is quantized separately from the other images
430 The index in the global colormap of the logical screen's background
431 color. This is only set if the current image uses the global
432 colormap. You can set this on write too, but for it to choose the
433 color you want, you will need to supply only paletted images and set
434 the C<gif_eliminate_unused> tag to 0.
436 =item gif_trans_index
438 The index of the color in the colormap used for transparency. If the
439 image has a transparency then it is returned as a 4 channel image with
440 the alpha set to zero in this palette entry. This value is not used
441 when writing. ("Transparent Color Index")
443 =item gif_trans_color
445 A reference to an Imager::Color object, which is the colour to use for
446 the palette entry used to represent transparency in the palette. You
447 need to set the transp option (see L<Quantization options>) for this
452 The delay until the next frame is displayed, in 1/100 of a second.
457 whether or not a user input is expected before continuing (view dependent)
462 how the next frame is displayed ("Disposal Method")
466 the number of loops from the Netscape Loop extension. This may be zero.
470 the first block of the first gif comment before each image.
472 =item gif_eliminate_unused
474 If this is true, when you write a paletted image any unused colors
475 will be eliminated from its palette. This is set by default.
479 Where applicable, the ("name") is the name of that field from the GIF89
482 The following gif writing options are obsolete, you should set the
483 corresponding tag in the image, either by using the tags functions, or
484 by supplying the tag and value as options.
488 =item gif_each_palette
490 Each image in the gif file has it's own palette if this is non-zero.
491 All but the first image has a local colour table (the first uses the
494 Use C<gif_local_map> in new code.
498 The images are written interlaced if this is non-zero.
500 Use C<gif_interlace> in new code.
504 A reference to an array containing the delays between images, in 1/100
507 Use C<gif_delay> in new code.
511 A reference to an array of references to arrays which represent screen
512 positions for each image.
514 New code should use the C<gif_left> and C<gif_top> tags.
518 If this is non-zero the Netscape loop extension block is generated,
519 which makes the animation of the images repeat.
521 This is currently unimplemented due to some limitations in giflib.
525 You can supply a C<page> parameter to the C<read()> method to read
526 some page other than the first. The page is 0 based:
528 # read the second image in the file
529 $image->read(file=>"example.gif", page=>1)
530 or die "Cannot read second page: ",$image->errstr,"\n";
532 Before release 0.46, Imager would read multi-image GIF image files
533 into a single image, overlaying each of the images onto the virtual
536 As of 0.46 the default is to read the first image from the file, as if
537 called with C<< page => 0 >>.
539 You can return to the previous behaviour by calling read with the
540 C<gif_consolidate> parameter set to a true value:
542 $img->read(file=>$some_gif_file, gif_consolidate=>1);
544 =head2 TIFF (Tagged Image File Format)
546 Imager can write images to either paletted or RGB TIFF images,
547 depending on the type of the source image. Currently if you write a
548 16-bit/sample or double/sample image it will be written as an
549 8-bit/sample image. Only 1 or 3 channel images can be written.
551 If you are creating images for faxing you can set the I<class>
552 parameter set to C<fax>. By default the image is written in fine
553 mode, but this can be overridden by setting the I<fax_fine> parameter
554 to zero. Since a fax image is bi-level, Imager uses a threshold to
555 decide if a given pixel is black or white, based on a single channel.
556 For greyscale images channel 0 is used, for color images channel 1
557 (green) is used. If you want more control over the conversion you can
558 use $img->to_paletted() to product a bi-level image. This way you can
561 my $bilevel = $img->to_paletted(colors=>[ NC(0,0,0), NC(255,255,255) ],
562 make_colors => 'none',
563 translate => 'errdiff',
564 errdiff => 'stucki');
570 If set to 'fax' the image will be written as a bi-level fax image.
574 By default when I<class> is set to 'fax' the image is written in fine
575 mode, you can select normal mode by setting I<fax_fine> to 0.
579 Imager should be able to read any TIFF image you supply. Paletted
580 TIFF images are read as paletted Imager images, since paletted TIFF
581 images have 16-bits/sample (48-bits/color) this means the bottom
582 8-bits are lost, but this shouldn't be a big deal. Currently all
583 direct color images are read at 8-bits/sample.
585 TIFF supports the spatial resolution tags. See the
586 C<tiff_resolutionunit> tag for some extra options.
588 The following tags are set in a TIFF image when read, and can be set
593 =item tiff_resolutionunit
595 The value of the ResolutionUnit tag. This is ignored on writing if
596 the i_aspect_only tag is non-zero.
598 The C<i_xres> and C<i_yres> tags are expressed in pixels per inch no
599 matter the value of this tag, they will be converted to/from the value
600 stored in the TIFF file.
602 =item tiff_resolutionunit_name
604 This is set when reading a TIFF file to the name of the unit given by
605 C<tiff_resolutionunit>. Possible results include C<inch>,
606 C<centimeter>, C<none> (the C<i_aspect_only> tag is also set reading
607 these files) or C<unknown>.
609 =item tiff_bitspersample
611 Bits per sample from the image. This value is not used when writing
612 an image, it is only set on a read image.
614 =item tiff_photometric
616 Value of the PhotometricInterpretation tag from the image. This value
617 is not used when writing an image, it is only set on a read image.
619 =item tiff_documentname
621 =item tiff_imagedescription
635 =item tiff_hostcomputer
637 Various strings describing the image. tiff_datetime must be formatted
638 as "YYYY:MM:DD HH:MM:SS". These correspond directly to the mixed case
639 names in the TIFF specification. These are set in images read from a
640 TIFF and saved when writing a TIFF image.
642 You can supply a C<page> parameter to the C<read()> method to read
643 some page other than the first. The page is 0 based:
645 # read the second image in the file
646 $image->read(file=>"example.tif", page=>1)
647 or die "Cannot read second page: ",$image->errstr,"\n";
653 Imager can write 24-bit RGB, and 8, 4 and 1-bit per pixel paletted
654 Windows BMP files. Currently you cannot write compressed BMP files
657 Imager can read 24-bit RGB, and 8, 4 and 1-bit perl pixel paletted
658 Windows BMP files. There is some support for reading 16-bit per pixel
659 images, but I haven't found any for testing.
661 BMP has no support for multi-image files.
663 BMP files support the spatial resolution tags, but since BMP has no
664 support for storing only an aspect ratio, if C<i_aspect_only> is set
665 when you write the C<i_xres> and C<i_yres> values are scaled so the
668 The following tags are set when you read an image from a BMP file:
672 =item bmp_compression
674 The type of compression, if any. This can be any of the following
685 8-bits/pixel paletted value RLE compression.
689 4-bits/pixel paletted value RLE compression.
691 =item BI_BITFIELDS (3)
697 =item bmp_compression_name
699 The bmp_compression value as a BI_* string
701 =item bmp_important_colors
703 The number of important colors as defined by the writer of the image.
705 =item bmp_used_colors
707 Number of color used from the BMP header
711 The file size from the BMP header
715 Number of bits stored per pixel. (24, 8, 4 or 1)
721 When storing targa images rle compression can be activated with the
722 'compress' parameter, the 'idstring' parameter can be used to set the
723 targa comment field and the 'wierdpack' option can be used to use the
724 15 and 16 bit targa formats for rgb and rgba data. The 15 bit format
725 has 5 of each red, green and blue. The 16 bit format in addition
726 allows 1 bit of alpha. The most significant bits are used for each
744 When reading raw images you need to supply the width and height of the
745 image in the xsize and ysize options:
747 $img->read(file=>'foo.raw', xsize=>100, ysize=>100)
748 or die "Cannot read raw image\n";
750 If your input file has more channels than you want, or (as is common),
751 junk in the fourth channel, you can use the datachannels and
752 storechannels options to control the number of channels in your input
753 file and the resulting channels in your image. For example, if your
754 input image uses 32-bits per pixel with red, green, blue and junk
755 values for each pixel you could do:
757 $img->read(file=>'foo.raw', xsize=>100, ysize=>100, datachannels=>4,
759 or die "Cannot read raw image\n";
761 Normally the raw image is expected to have the value for channel 1
762 immediately following channel 0 and channel 2 immediately following
763 channel 1 for each pixel. If your input image has all the channel 0
764 values for the first line of the image, followed by all the channel 1
765 values for the first line and so on, you can use the interleave option:
767 $img->read(file=>'foo.raw', xsize=100, ysize=>100, interleave=>1)
768 or die "Cannot read raw image\n";
772 There are no PNG specific tags.
776 =head2 Producing an image from a CGI script
778 Once you have an image the basic mechanism is:
784 set STDOUT to autoflush
788 output a content-type header, and optionally a content-length header
792 put STDOUT into binmode
796 call write() with the C<fd> or C<fh> parameter. You will need to
797 provide the C<type> parameter since Imager can't use the extension to
798 guess the file format you want.
802 # write an image from a CGI script
804 use CGI qw(:standard);
807 print header(-type=>'image/gif');
808 $img->write(type=>'gif', fd=>fileno(STDOUT))
811 If you want to send a content length you can send the output to a
812 scalar to get the length:
815 $img->write(type=>'gif', data=>\$data)
818 print header(-type=>'image/gif', -content_length=>length($data));
821 =head2 Writing an animated GIF
823 The basic idea is simple, just use write_multi():
826 Imager->write_multi({ file=>$filename, type=>'gif' }, @imgs);
828 If your images are RGB images the default quantization mechanism will
829 produce a very good result, but can take a long time to execute. You
830 could either use the standard webmap:
832 Imager->write_multi({ file=>$filename,
834 make_colors=>'webmap' },
837 or use a median cut algorithm to built a fairly optimal color map:
839 Imager->write_multi({ file=>$filename,
841 make_colors=>'mediancut' },
844 By default all of the images will use the same global colormap, which
845 will produce a smaller image. If your images have significant color
846 differences, you may want to generate a new palette for each image:
848 Imager->write_multi({ file=>$filename,
850 make_colors=>'mediancut',
851 gif_local_map => 1 },
854 which will set the C<gif_local_map> tag in each image to 1.
855 Alternatively, if you know only some images have different colors, you
856 can set the tag just for those images:
858 $imgs[2]->settag(name=>'gif_local_map', value=>1);
859 $imgs[4]->settag(name=>'gif_local_map', value=>1);
861 and call write_multi() without a C<gif_local_map> parameter, or supply
862 an arrayref of values for the tag:
864 Imager->write_multi({ file=>$filename,
866 make_colors=>'mediancut',
867 gif_local_map => [ 0, 0, 1, 0, 1 ] },
870 Other useful parameters include C<gif_delay> to control the delay
871 between frames and C<transp> to control transparency.
873 =head2 Reading tags after reading an image
875 This is pretty simple:
877 # print the author of a TIFF, if any
878 my $img = Imager->new;
879 $img->read(file=>$filename, type='tiff') or die $img->errstr;
880 my $author = $img->tags(name=>'tiff_author');
881 if (defined $author) {
882 print "Author: $author\n";
887 When saving Gif images the program does NOT try to shave of extra
888 colors if it is possible. If you specify 128 colors and there are
889 only 2 colors used - it will have a 128 colortable anyway.