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;
23 You can read and write a variety of images formats, assuming you have
24 the appropriate libraries, and images can be read or written to/from
25 files, file handles, file descriptors, scalars, or through callbacks.
27 To see which image formats Imager is compiled to support the following
28 code snippet is sufficient:
31 print join " ", keys %Imager::formats;
33 This will include some other information identifying libraries rather
36 Reading writing to and from files is simple, use the C<read()>
37 method to read an image:
39 my $img = Imager->new;
40 $img->read(file=>$filename, type=>$type)
41 or die "Cannot read $filename: ", $img->errstr;
43 and the C<write()> method to write an image:
45 $img->write(file=>$filename, type=>$type)
46 or die "Cannot write $filename: ", $img->errstr;
48 If you're reading from a format that supports multiple images per
49 file, use the C<read_multi()> method:
51 my @imgs = Imager->read_multi(file=>$filename, type=>$type)
52 or die "Cannot read $filename: ", Imager->errstr;
54 and if you want to write multiple images to a single file use the
55 C<write_multi()> method:
57 Imager->write_multi({ file=> $filename, type=>$type }, @images)
58 or die "Cannot write $filename: ", Imager->errstr;
60 If the I<filename> includes an extension that Imager recognizes, then
61 you don't need the I<type>, but you may want to provide one anyway.
62 See L</Guessing types> for information on controlling this
65 The C<type> parameter is a lowercase representation of the file type,
66 and can be any of the following:
68 bmp Windows BitMaP (BMP)
69 gif Graphics Interchange Format (GIF)
71 png Portable Network Graphics (PNG)
72 pnm Portable aNyMap (PNM)
76 tiff Tagged Image File Format (TIFF)
78 When you read an image, Imager may set some tags, possibly including
79 information about the spatial resolution, textual information, and
80 animation information. See L<Imager::ImageTypes/Tags> for specifics.
82 =head2 Input and output
84 When reading or writing you can specify one of a variety of sources or
91 The C<file> parameter is the name of the image file to be written to
92 or read from. If Imager recognizes the extension of the file you do
93 not need to supply a C<type>.
97 C<fh> is a file handle, typically either returned from
98 C<<IO::File->new()>>, or a glob from an C<open> call. You should call
99 C<binmode> on the handle before passing it to Imager.
101 Imager will set the handle to autoflush to make sure any buffered data
102 is flushed , since Imager will write to the file descriptor (from
103 fileno()) rather than writing at the perl level.
107 C<fd> is a file descriptor. You can get this by calling the
108 C<fileno()> function on a file handle, or by using one of the standard
109 file descriptor numbers.
111 If you get this from a perl file handle, you may need to flush any
112 buffered output, otherwise it may appear in the output stream after
117 When reading data, C<data> is a scalar containing the image file data,
118 when writing, C<data> is a reference to the scalar to save the image
119 file data too. For GIF images you will need giflib 4 or higher, and
120 you may need to patch giflib to use this option for writing.
124 Imager will make calls back to your supplied coderefs to read, write
125 and seek from/to/through the image file.
127 When reading from a file you can use either C<callback> or C<readcb>
128 to supply the read callback, and when writing C<callback> or
129 C<writecb> to supply the write callback.
131 When writing you can also supply the C<maxbuffer> option to set the
132 maximum amount of data that will be buffered before your write
133 callback is called. Note: the amount of data supplied to your
134 callback can be smaller or larger than this size.
136 The read callback is called with 2 parameters, the minimum amount of
137 data required, and the maximum amount that Imager will store in it's C
138 level buffer. You may want to return the minimum if you have a slow
139 data source, or the maximum if you have a fast source and want to
140 prevent many calls to your perl callback. The read data should be
141 returned as a scalar.
143 Your write callback takes exactly one parameter, a scalar containing
144 the data to be written. Return true for success.
146 The seek callback takes 2 parameters, a I<POSITION>, and a I<WHENCE>,
147 defined in the same way as perl's seek function.
149 You can also supply a C<closecb> which is called with no parameters
150 when there is no more data to be written. This could be used to flush
155 =head2 Guessing types
157 Imager uses the code reference in $Imager::FORMATGUESS to guess the
158 file type when you don't supply a C<type>. The code reference is
159 called with a single parameter, the filename of the file. The code
160 reference is only called if a C<file> parameter is supplied to the
163 Return either a valid Imager file type, or undef.
165 # I'm writing jpegs to weird filenames
166 local $Imager::FORMATGUESS = sub { 'jpeg' };
168 =head1 TYPE SPECIFIC INFORMATION
170 The different image formats can write different image type, and some have
171 different options to control how the images are written.
173 When you call C<write()> or C<write_multi()> with an option that has
174 the same name as a tag for the image format you're writing, then the
175 value supplied to that option will be used to set the corresponding
176 tag in the image. Depending on the image format, these values will be
177 used when writing the image.
179 This replaces the previous options that were used when writing GIF
180 images. Currently if you use an obsolete option, it will be converted
181 to the equivalent tag and Imager will produced a warning. You can
182 suppress these warnings by calling the C<Imager::init()> function with
183 the C<warn_obsolete> option set to false:
185 Imager::init(warn_obsolete=>0);
187 At some point in the future these obsolete options will no longer be
190 =head2 PNM (Portable aNy Map)
192 Imager can write PGM (Portable Gray Map) and PPM (Portable PixMaps)
193 files, depending on the number of channels in the image. Currently
194 the images are written in binary formats. Only 1 and 3 channel images
195 can be written, including 1 and 3 channel paletted images.
197 $img->write(file=>'foo.ppm') or die $img->errstr;
199 Imager can read both the ASCII and binary versions of each of the PBM
200 (Portable BitMap), PGM and PPM formats.
202 $img->read(file=>'foo.ppm') or die $img->errstr;
204 PNM does not support the spatial resolution tags.
208 You can supply a C<jpegquality> parameter (0-100) when writing a JPEG
209 file, which defaults to 75%. Only 1 and 3 channel images
210 can be written, including 1 and 3 channel paletted images.
212 $img->write(file=>'foo.jpg', jpegquality=>90) or die $img->errstr;
214 Imager will read a grayscale JPEG as a 1 channel image and a color
215 JPEG as a 3 channel image.
217 $img->read(file=>'foo.jpg') or die $img->errstr;
219 PNM does not support the spatial resolution tags.
221 =head2 GIF (Graphics Interchange Format)
223 When writing one of more GIF images you can use the same
224 L<Quantization Options|Imager::ImageTypes> as you can when converting
225 an RGB image into a paletted image.
227 When reading a GIF all of the sub-images are combined using the screen
228 size and image positions into one big image, producing an RGB image.
229 This may change in the future to produce a paletted image where possible.
231 When you read a single GIF with C<$img-E<gt>read()> you can supply a
232 reference to a scalar in the C<colors> parameter, if the image is read
233 the scalar will be filled with a reference to an anonymous array of
234 L<Imager::Color> objects, representing the palette of the image. This
235 will be the first palette found in the image. If you want the
236 palettes for each of the images in the file, use C<read_multi()> and
237 use the C<getcolors()> method on each image.
239 GIF does not support the spatial resolution tags.
241 Imager will set the following tags in each image when reading, and can
242 use most of them when writing to GIF:
248 the offset of the image from the left of the "screen" ("Image Left
253 the offset of the image from the top of the "screen" ("Image Top Position")
257 non-zero if the image was interlaced ("Interlace Flag")
259 =item gif_screen_width
261 =item gif_screen_height
263 the size of the logical screen. When writing this is used as the
264 minimum. If any image being written would extend beyond this the
265 screen size is extended. ("Logical Screen Width", "Logical Screen
268 When writing this is used as a minimum, if the combination of the
269 image size and the image's C<gif_left> and C<gif_top> is beyond this
270 size then the screen size will be expanded.
274 Non-zero if this image had a local color map. If set for an image
275 when writing the image is quantized separately from the other images
280 The index in the global colormap of the logical screen's background
281 color. This is only set if the current image uses the global
282 colormap. You can set this on write too, but for it to choose the
283 color you want, you will need to supply only paletted images and set
284 the C<gif_eliminate_unused> tag to 0.
286 =item gif_trans_index
288 The index of the color in the colormap used for transparency. If the
289 image has a transparency then it is returned as a 4 channel image with
290 the alpha set to zero in this palette entry. This value is not used
291 when writing. ("Transparent Color Index")
293 =item gif_trans_color
295 A reference to an Imager::Color object, which is the colour to use for
296 the palette entry used to represent transparency in the palette. You
297 need to set the transp option (see L<Quantization options>) for this
302 The delay until the next frame is displayed, in 1/100 of a second.
307 whether or not a user input is expected before continuing (view dependent)
312 how the next frame is displayed ("Disposal Method")
316 the number of loops from the Netscape Loop extension. This may be zero.
320 the first block of the first gif comment before each image.
322 =item gif_eliminate_unused
324 If this is true, when you write a paletted image any unused colors
325 will be eliminated from its palette. This is set by default.
329 Where applicable, the ("name") is the name of that field from the GIF89
332 The following gif writing options are obsolete, you should set the
333 corresponding tag in the image, either by using the tags functions, or
334 by supplying the tag and value as options.
338 =item gif_each_palette
340 Each image in the gif file has it's own palette if this is non-zero.
341 All but the first image has a local colour table (the first uses the
344 Use C<gif_local_map> in new code.
348 The images are written interlaced if this is non-zero.
350 Use C<gif_interlace> in new code.
354 A reference to an array containing the delays between images, in 1/100
357 Use C<gif_delay> in new code.
361 A reference to an array of references to arrays which represent screen
362 positions for each image.
364 New code should use the C<gif_left> and C<gif_top> tags.
368 If this is non-zero the Netscape loop extension block is generated,
369 which makes the animation of the images repeat.
371 This is currently unimplemented due to some limitations in giflib.
375 =head2 TIFF (Tagged Image File Format)
377 Imager can write images to either paletted or RGB TIFF images,
378 depending on the type of the source image. Currently if you write a
379 16-bit/sample or double/sample image it will be written as an
380 8-bit/sample image. Only 1 or 3 channel images can be written.
382 If you are creating images for faxing you can set the I<class>
383 parameter set to C<fax>. By default the image is written in fine
384 mode, but this can be overridden by setting the I<fax_fine> parameter
385 to zero. Since a fax image is bi-level, Imager uses a threshold to
386 decide if a given pixel is black or white, based on a single channel.
387 For greyscale images channel 0 is used, for color images channel 1
388 (green) is used. If you want more control over the conversion you can
389 use $img->to_paletted() to product a bi-level image. This way you can
392 my $bilevel = $img->to_paletted(colors=>[ NC(0,0,0), NC(255,255,255) ],
393 make_colors => 'none',
394 translate => 'errdiff',
395 errdiff => 'stucki');
401 If set to 'fax' the image will be written as a bi-level fax image.
405 By default when I<class> is set to 'fax' the image is written in fine
406 mode, you can select normal mode by setting I<fax_fine> to 0.
410 Imager should be able to read any TIFF image you supply. Paletted
411 TIFF images are read as paletted Imager images, since paletted TIFF
412 images have 16-bits/sample (48-bits/color) this means the bottom
413 8-bits are lost, but this shouldn't be a big deal. Currently all
414 direct color images are read at 8-bits/sample.
416 TIFF supports the spatial resolution tags. See the
417 C<tiff_resolutionunit> tag for some extra options.
419 The following tags are set in a TIFF image when read, and can be set
424 =item tiff_resolutionunit
426 The value of the ResolutionUnit tag. This is ignored on writing if
427 the i_aspect_only tag is non-zero.
429 The C<i_xres> and C<i_yres> tags are expressed in pixels per inch no
430 matter tha value of this tag, they will be converted to/from the value
431 stored in the TIFF file.
433 =item tiff_documentname
435 =item tiff_imagedescription
449 =item tiff_hostcomputer
451 Various strings describing the image. tiff_datetime must be formatted
452 as "YYYY:MM:DD HH:MM:SS". These correspond directly to the mixed case
453 names in the TIFF specification. These are set in images read from a
454 TIFF and saved when writing a TIFF image.
460 Imager can write 24-bit RGB, and 8, 4 and 1-bit per pixel paletted
461 Windows BMP files. Currently you cannot write compressed BMP files
464 Imager can read 24-bit RGB, and 8, 4 and 1-bit perl pixel paletted
465 Windows BMP files. There is some support for reading 16-bit per pixel
466 images, but I haven't found any for testing.
468 BMP has no support for multi-image files.
470 BMP files support the spatial resolution tags, but since BMP has no
471 support for storing only an aspect ratio, if C<i_aspect_only> is set
472 when you write the C<i_xres> and C<i_yres> values are scaled so the
475 The following tags are set when you read an image from a BMP file:
479 =item bmp_compression
481 The type of compression, if any. This can be any of the following
492 8-bits/pixel paletted value RLE compression.
496 4-bits/pixel paletted value RLE compression.
498 =item BI_BITFIELDS (3)
504 =item bmp_important_colors
506 The number of important colors as defined by the writer of the image.
512 When storing targa images rle compression can be activated with the
513 'compress' parameter, the 'idstring' parameter can be used to set the
514 targa comment field and the 'wierdpack' option can be used to use the
515 15 and 16 bit targa formats for rgb and rgba data. The 15 bit format
516 has 5 of each red, green and blue. The 16 bit format in addition
517 allows 1 bit of alpha. The most significant bits are used for each
537 When reading raw images you need to supply the width and height of the
538 image in the xsize and ysize options:
540 $img->read(file=>'foo.raw', xsize=>100, ysize=>100)
541 or die "Cannot read raw image\n";
543 If your input file has more channels than you want, or (as is common),
544 junk in the fourth channel, you can use the datachannels and
545 storechannels options to control the number of channels in your input
546 file and the resulting channels in your image. For example, if your
547 input image uses 32-bits per pixel with red, green, blue and junk
548 values for each pixel you could do:
550 $img->read(file=>'foo.raw', xsize=>100, ysize=>100, datachannels=>4,
552 or die "Cannot read raw image\n";
554 Normally the raw image is expected to have the value for channel 1
555 immediately following channel 0 and channel 2 immediately following
556 channel 1 for each pixel. If your input image has all the channel 0
557 values for the first line of the image, followed by all the channel 1
558 values for the first line and so on, you can use the interleave option:
560 $img->read(file=>'foo.raw', xsize=100, ysize=>100, interleave=>1)
561 or die "Cannot read raw image\n";
565 =head2 Producing an image from a CGI script
567 Once you have an image the basic mechanism is:
573 set STDOUT to autoflush
577 output a content-type header, and optionally a content-length header
581 put STDOUT into binmode
585 call write() with the C<fd> or C<fh> parameter. You will need to
586 provide the C<type> parameter since
590 # write an image from a CGI script
592 use CGI qw(:standard);
595 print header(-type=>'image/gif');
596 $img->write(type=>'gif', fd=>fileno(STDOUT))
599 If you want to send a content length you can send the output to a
600 scalar to get the length:
603 $img->write(type=>'gif', data=>\$data)
606 print header(-type=>'image/gif', -content_length=>length($data));
609 =head2 Writing an animated GIF
611 The basic idea is simple, just use write_multi():
614 Imager->write_multi({ file=>$filename, type=>'gif' }, @imgs);
616 If your images are RGB images the default quantization mechanism will
617 produce a very good result, but can take a long time to execute. You
618 could either use the standard webmap:
620 Imager->write_multi({ file=>$filename,
622 make_colors=>'webmap' },
625 or use a median cut algorithm to built a fairly optimal color map:
627 Imager->write_multi({ file=>$filename,
629 make_colors=>'mediancut' },
632 By default all of the images will use the same global colormap, which
633 will produce a smaller image. If your images have significant color
634 differences, you may want to generate a new palette for each image:
636 Imager->write_multi({ file=>$filename,
638 make_colors=>'mediancut',
639 gif_local_map => 1 },
642 which will set the C<gif_local_map> tag in each image to 1.
643 Alternatively, if you know only some images have different colors, you
644 can set the tag just for those images:
646 $imgs[2]->settag(name=>'gif_local_map', value=>1);
647 $imgs[4]->settag(name=>'gif_local_map', value=>1);
649 and call write_multi() without a C<gif_local_map> parameter, or supply
650 an arrayref of values for the tag:
652 Imager->write_multi({ file=>$filename,
654 make_colors=>'mediancut',
655 gif_local_map => [ 0, 0, 1, 0, 1 ] },
658 Other useful parameters include C<gif_delay> to control the delay
659 between frames and C<transp> to control transparency.
661 =head2 Reading tags after reading an image
663 This is pretty simple:
665 # print the author of a TIFF, if any
666 my $img = Imager->new;
667 $img->read(file=>$filename, type='tiff') or die $img->errstr;
668 my $author = $img->tags(name=>'tiff_author');
669 if (defined $author) {
670 print "Author: $author\n";
675 When saving Gif images the program does NOT try to shave of extra
676 colors if it is possible. If you specify 128 colors and there are
677 only 2 colors used - it will have a 128 colortable anyway.