]> git.imager.perl.org - imager.git/blob - lib/Imager/Files.pod
only prepend ./ to font filenames when passing them to T1Lib and
[imager.git] / lib / Imager / Files.pod
1 =head1 NAME
2
3 Imager::Files - working with image files
4
5 =head1 SYNOPSIS
6
7   use Imager;
8   my $img = ...;
9   $img->write(file=>$filename, type=>$type)
10     or die "Cannot write: ",$img->errstr;
11
12   # type is optional if we can guess the format from the filename
13   $img->write(file => "foo.png")
14     or die "Cannot write: ",$img->errstr;
15
16   $img = Imager->new;
17   $img->read(file=>$filename, type=>$type)
18     or die "Cannot read: ", $img->errstr;
19
20   # type is optional if we can guess the type from the file data
21   # and we normally can guess
22   $img->read(file => $filename)
23     or die "Cannot read: ", $img->errstr;
24
25   Imager->write_multi({ file=> $filename, ... }, @images)
26     or die "Cannot write: ", Imager->errstr;
27
28   my @imgs = Imager->read_multi(file=>$filename)
29     or die "Cannot read: ", Imager->errstr;
30
31   Imager->set_file_limits(width=>$max_width, height=>$max_height)
32
33   my @read_types = Imager->read_types;
34   my @write_types = Imager->write_types;
35
36   # we can write/write_multi to things other than filenames
37   my $data;
38   $img->write(data => \$data, type => $type) or die;
39
40   my $fh = ... ; # eg. IO::File
41   $img->write(fh => $fh, type => $type) or die;
42
43   $img->write(fd => fileno($fh), type => $type) or die;
44
45   # some file types need seek callbacks too
46   $img->write(callback => \&write_callback, type => $type) or die;
47
48   # and similarly for read/read_multi
49   $img->read(data => $data) or die;
50   $img->read(fh => $fh) or die;
51   $img->read(fd => fileno($fh)) or die;
52   $img->read(callback => \&read_callback) or die;
53
54   use Imager 0.68;
55   my $img = Imager->new(file => $filename)
56     or die Imager->errstr;
57
58 =head1 DESCRIPTION
59
60 You can read and write a variety of images formats, assuming you have
61 the appropriate libraries, and images can be read or written to/from
62 files, file handles, file descriptors, scalars, or through callbacks.
63
64 To see which image formats Imager is compiled to support the following
65 code snippet is sufficient:
66
67   use Imager;
68   print join " ", keys %Imager::formats;
69
70 This will include some other information identifying libraries rather
71 than file formats.  For new code you might find the L</read_types> or
72 L</write_types> methods useful.
73
74 =over 
75
76 =item read
77
78 Reading writing to and from files is simple, use the C<read()>
79 method to read an image:
80
81   my $img = Imager->new;
82   $img->read(file=>$filename, type=>$type)
83     or die "Cannot read $filename: ", $img->errstr;
84
85 In most cases Imager can auto-detect the file type, so you can just
86 supply the file name:
87
88   $img->read(file => $filename)
89     or die "Cannot read $filename: ", $img->errstr;
90
91 The read() method accepts the C<allow_partial> parameter.  If this is
92 non-zero then read() can return true on an incomplete image and set
93 the C<i_incomplete> tag.
94
95 From Imager 0.68 you can supply most read() parameters to the new()
96 method to read the image file on creation.  If the read fails, check
97 Imager->errstr() for the cause:
98
99   use Imager 0.68;
100   my $img = Imager->new(file => $filename)
101     or die "Cannot read $filename: ", Imager->errstr;
102
103 =item write
104
105 and the C<write()> method to write an image:
106
107   $img->write(file=>$filename, type=>$type)
108     or die "Cannot write $filename: ", $img->errstr;
109
110 =item read_multi
111
112 If you're reading from a format that supports multiple images per
113 file, use the C<read_multi()> method:
114
115   my @imgs = Imager->read_multi(file=>$filename, type=>$type)
116     or die "Cannot read $filename: ", Imager->errstr;
117
118 As with the read() method, Imager will normally detect the C<type>
119 automatically.
120
121 =item write_multi
122
123 and if you want to write multiple images to a single file use the
124 C<write_multi()> method:
125
126   Imager->write_multi({ file=> $filename, type=>$type }, @images)
127     or die "Cannot write $filename: ", Imager->errstr;
128
129 =item read_types
130
131 This is a class method that returns a list of the image file types
132 that Imager can read.
133
134   my @types = Imager->read_types;
135
136 These types are the possible values for the C<type> parameter, not
137 necessarily the extension of the files you're reading.
138
139 It is possible for extra file read handlers to be loaded when
140 attempting to read a file, which may modify the list of available read
141 types.
142
143 =item write_types
144
145 This is a class method that returns a list of the image file types
146 that Imager can write.
147
148   my @types = Imager->write_types;
149
150 Note that these are the possible values for the C<type> parameter, not
151 necessarily the extension of the files you're writing.
152
153 It is possible for extra file write handlers to be loaded when
154 attempting to write a file, which may modify the list of available
155 write types.
156
157 =back
158
159 When writing, if the C<filename> includes an extension that Imager
160 recognizes, then you don't need the C<type>, but you may want to
161 provide one anyway.  See L</Guessing types> for information on
162 controlling this recognition.
163
164 The C<type> parameter is a lowercase representation of the file type,
165 and can be any of the following:
166
167   bmp   Windows BitMaP (BMP)
168   gif   Graphics Interchange Format (GIF)
169   jpeg  JPEG/JFIF
170   png   Portable Network Graphics (PNG)
171   pnm   Portable aNyMap (PNM)
172   raw   Raw
173   sgi   SGI .rgb files
174   tga   TARGA
175   tiff  Tagged Image File Format (TIFF)
176
177 When you read an image, Imager may set some tags, possibly including
178 information about the spatial resolution, textual information, and
179 animation information.  See L<Imager::ImageTypes/Tags> for specifics.
180
181 The open() method is a historical alias for the read() method.
182
183 =head2 Input and output
184
185 When reading or writing you can specify one of a variety of sources or
186 targets:
187
188 =over
189
190 =item *
191
192 C<file> - The C<file> parameter is the name of the image file to be
193 written to or read from.  If Imager recognizes the extension of the
194 file you do not need to supply a C<type>.
195
196   # write in tiff format
197   $image->write(file => "example.tif")
198     or die $image->errstr;
199
200   $image->write(file => 'foo.tmp', type => 'tiff')
201     or die $image->errstr;
202
203   my $image = Imager->new;
204   $image->read(file => 'example.tif')
205     or die $image->errstr;
206
207 =item *
208
209 C<fh> - C<fh> is a file handle, typically either returned from
210 C<<IO::File->new()>>, or a glob from an C<open> call.  You should call
211 C<binmode> on the handle before passing it to Imager.
212
213 Imager will set the handle to autoflush to make sure any buffered data
214 is flushed , since Imager will write to the file descriptor (from
215 fileno()) rather than writing at the perl level.
216
217   $image->write(fh => \*STDOUT, type => 'gif')
218     or die $image->errstr;
219
220   # for example, a file uploaded via CGI.pm
221   $image->read(fd => $cgi->param('file')) 
222     or die $image->errstr;
223
224 =item *
225
226 C<fd> - C<fd> is a file descriptor.  You can get this by calling the
227 C<fileno()> function on a file handle, or by using one of the standard
228 file descriptor numbers.
229
230 If you get this from a perl file handle, you may need to flush any
231 buffered output, otherwise it may appear in the output stream after
232 the image.
233
234   $image->write(fd => file(STDOUT), type => 'gif')
235     or die $image->errstr;
236
237 =item *
238
239 C<data> - When reading data, C<data> is a scalar containing the image
240 file data, when writing, C<data> is a reference to the scalar to save
241 the image file data too.  For GIF images you will need C<giflib> 4 or
242 higher, and you may need to patch C<giflib> to use this option for
243 writing.
244
245   my $data;
246   $image->write(data => \$data, type => 'tiff')
247     or die $image->errstr;
248
249   my $data = $row->{someblob}; # eg. from a database
250   my @images = Imager->read_multi(data => $data)
251     or die Imager->errstr;
252
253 =item *
254
255 C<callback> - Imager will make calls back to your supplied coderefs to
256 read, write and seek from/to/through the image file.
257
258 When reading from a file you can use either C<callback> or C<readcb>
259 to supply the read callback, and when writing C<callback> or
260 C<writecb> to supply the write callback.
261
262 When writing you can also supply the C<maxbuffer> option to set the
263 maximum amount of data that will be buffered before your write
264 callback is called.  Note: the amount of data supplied to your
265 callback can be smaller or larger than this size.
266
267 The read callback is called with 2 parameters, the minimum amount of
268 data required, and the maximum amount that Imager will store in it's C
269 level buffer.  You may want to return the minimum if you have a slow
270 data source, or the maximum if you have a fast source and want to
271 prevent many calls to your perl callback.  The read data should be
272 returned as a scalar.
273
274 Your write callback takes exactly one parameter, a scalar containing
275 the data to be written.  Return true for success.
276
277 The seek callback takes 2 parameters, a I<POSITION>, and a I<WHENCE>,
278 defined in the same way as perl's seek function.
279
280 You can also supply a C<closecb> which is called with no parameters
281 when there is no more data to be written.  This could be used to flush
282 buffered data.
283
284   # contrived
285   my $data;
286   sub mywrite {
287     $data .= unpack("H*", shift);
288     1;
289   }
290   Imager->write_multi({ callback => \&mywrite, type => 'gif'}, @images)
291     or die Imager->errstr;
292
293 Note that for reading you'll almost always need to provide a
294 C<seekcb>.
295
296 =back
297
298 =head2 Guessing types
299
300 When writing to a file, if you don't supply a C<type> parameter Imager
301 will attempt to guess it from the file name.  This is done by calling
302 the code reference stored in C<$Imager::FORMATGUESS>.  This is only
303 done when write() or write_multi() is called with a C<file> parameter.
304
305 The default function value of C<$Imager::FORMATGUESS> is
306 C<\&Imager::def_guess_type>.
307
308 =over
309
310 =item def_guess_type
311
312 This is the default function Imager uses to derive a file type from a
313 file name.  This is a function, not a method.
314
315 Accepts a single parameter, the file name and returns the type or
316 undef.
317
318 =back
319
320 You can replace function with your own implementation if you have some
321 specialized need.  The function takes a single parameter, the name of
322 the file, and should return either a file type or under.
323
324   # I'm writing jpegs to weird filenames
325   local $Imager::FORMATGUESS = sub { 'jpeg' };
326
327 When reading a file Imager examines beginning of the file for
328 identifying information.  The current implementation attempts to
329 detect the following image types beyond those supported by Imager:
330
331 =for stopwords Photoshop
332
333 =over
334
335 C<xpm>, C<mng>, C<jng>, C<ilbm>, C<pcx>, C<fits>, C<psd> (Photoshop), C<eps>, Utah
336 C<RLE>.
337
338 =back
339
340 =head2 Limiting the sizes of images you read
341
342 =over
343
344 =item set_file_limits
345
346 In some cases you will be receiving images from an untested source,
347 such as submissions via CGI.  To prevent such images from consuming
348 large amounts of memory, you can set limits on the dimensions of
349 images you read from files:
350
351 =over
352
353 =item *
354
355 width - limit the width in pixels of the image
356
357 =item *
358
359 height - limit the height in pixels of the image
360
361 =item *
362
363 bytes - limits the amount of storage used by the image.  This depends
364 on the width, height, channels and sample size of the image.  For
365 paletted images this is calculated as if the image was expanded to a
366 direct color image.
367
368 =back
369
370 To set the limits, call the class method set_file_limits:
371
372   Imager->set_file_limits(width=>$max_width, height=>$max_height);
373
374 You can pass any or all of the limits above, any limits you do not
375 pass are left as they were.
376
377 Any limit of zero is treated as unlimited.
378
379 By default, all of the limits are zero, or unlimited.
380
381 You can reset all of the limited to their defaults by passing in the
382 reset parameter as a true value:
383
384   # no limits
385   Imager->set_file_limits(reset=>1);
386
387 This can be used with the other limits to reset all but the limit you
388 pass:
389
390   # only width is limited
391   Imager->set_file_limits(reset=>1, width=>100);
392
393   # only bytes is limited
394   Imager->set_file_limits(reset=>1, bytes=>10_000_000);
395
396 =item get_file_limits
397
398 You can get the current limits with the get_file_limits() method:
399
400   my ($max_width, $max_height, $max_bytes) =
401      Imager->get_file_limits();
402
403 =back
404
405 =head1 TYPE SPECIFIC INFORMATION
406
407 The different image formats can write different image type, and some have
408 different options to control how the images are written.
409
410 When you call C<write()> or C<write_multi()> with an option that has
411 the same name as a tag for the image format you're writing, then the
412 value supplied to that option will be used to set the corresponding
413 tag in the image.  Depending on the image format, these values will be
414 used when writing the image.
415
416 This replaces the previous options that were used when writing GIF
417 images.  Currently if you use an obsolete option, it will be converted
418 to the equivalent tag and Imager will produced a warning.  You can
419 suppress these warnings by calling the C<Imager::init()> function with
420 the C<warn_obsolete> option set to false:
421
422   Imager::init(warn_obsolete=>0);
423
424 At some point in the future these obsolete options will no longer be
425 supported.
426
427 =for stopwords aNy PixMaps BitMap
428
429 =head2 PNM (Portable aNy Map)
430
431 Imager can write C<PGM> (Portable Gray Map) and C<PPM> (Portable
432 PixMaps) files, depending on the number of channels in the image.
433 Currently the images are written in binary formats.  Only 1 and 3
434 channel images can be written, including 1 and 3 channel paletted
435 images.
436
437   $img->write(file=>'foo.ppm') or die $img->errstr;
438
439 Imager can read both the ASCII and binary versions of each of the
440 C<PBM> (Portable BitMap), C<PGM> and C<PPM> formats.
441
442   $img->read(file=>'foo.ppm') or die $img->errstr;
443
444 PNM does not support the spatial resolution tags.
445
446 The following tags are set when reading a PNM file:
447
448 =over
449
450 =item *
451
452 X<pnm_maxval>C<pnm_maxval> - the C<maxvals> number from the PGM/PPM header.
453 Always set to 2 for a C<PBM> file.
454
455 =item *
456
457 X<pnm_type>C<pnm_type> - the type number from the C<PNM> header, 1 for ASCII
458 C<PBM> files, 2 for ASCII C<PGM> files, 3 for ASCII c<PPM> files, 4 for binary
459 C<PBM> files, 5 for binary C<PGM> files, 6 for binary C<PPM> files.
460
461 =back
462
463 The following tag is checked when writing an image with more than
464 8-bits/sample:
465
466 =over
467
468 =item *
469
470 X<pnm_write_wide_data>pnm_write_wide_data - if this is non-zero then
471 write() can write C<PGM>/C<PPM> files with 16-bits/sample.  Some
472 applications, for example GIMP 2.2, and tools can only read
473 8-bit/sample binary PNM files, so Imager will only write a 16-bit
474 image when this tag is non-zero.
475
476 =back
477
478 =head2 JPEG
479
480 =for stopwords composited
481
482 You can supply a C<jpegquality> parameter (0-100) when writing a JPEG
483 file, which defaults to 75%.  If you write an image with an alpha
484 channel to a JPEG file then it will be composited against the
485 background set by the C<i_background> parameter (or tag).
486
487   $img->write(file=>'foo.jpg', jpegquality=>90) or die $img->errstr;
488
489 Imager will read a gray scale JPEG as a 1 channel image and a color
490 JPEG as a 3 channel image.
491
492   $img->read(file=>'foo.jpg') or die $img->errstr;
493
494 The following tags are set in a JPEG image when read, and can be set
495 to control output:
496
497 =over
498
499 =item C<jpeg_density_unit>
500
501 The value of the density unit field in the C<JFIF> header.  This is
502 ignored on writing if the C<i_aspect_only> tag is non-zero.
503
504 The C<i_xres> and C<i_yres> tags are expressed in pixels per inch no
505 matter the value of this tag, they will be converted to/from the value
506 stored in the JPEG file.
507
508 =item C<jpeg_density_unit_name>
509
510 This is set when reading a JPEG file to the name of the unit given by
511 C<jpeg_density_unit>.  Possible results include C<inch>,
512 C<centimeter>, C<none> (the C<i_aspect_only> tag is also set reading
513 these files).  If the value of C<jpeg_density_unit> is unknown then
514 this tag isn't set.
515
516 =item C<jpeg_comment>
517
518 Text comment.
519
520 =back
521
522 JPEG supports the spatial resolution tags C<i_xres>, C<i_yres> and
523 C<i_aspect_only>.
524
525 =for stopwords EXIF
526
527 If an C<APP1> block containing EXIF information is found, then any of the
528 following tags can be set:
529
530 =over
531
532 exif_aperture exif_artist exif_brightness exif_color_space
533 exif_contrast exif_copyright exif_custom_rendered exif_date_time
534 exif_date_time_digitized exif_date_time_original
535 exif_digital_zoom_ratio exif_exposure_bias exif_exposure_index
536 exif_exposure_mode exif_exposure_program exif_exposure_time
537 exif_f_number exif_flash exif_flash_energy exif_flashpix_version
538 exif_focal_length exif_focal_length_in_35mm_film
539 exif_focal_plane_resolution_unit exif_focal_plane_x_resolution
540 exif_focal_plane_y_resolution exif_gain_control exif_image_description
541 exif_image_unique_id exif_iso_speed_rating exif_make exif_max_aperture
542 exif_metering_mode exif_model exif_orientation exif_related_sound_file
543 exif_resolution_unit exif_saturation exif_scene_capture_type
544 exif_sensing_method exif_sharpness exif_shutter_speed exif_software
545 exif_spectral_sensitivity exif_sub_sec_time
546 exif_sub_sec_time_digitized exif_sub_sec_time_original
547 exif_subject_distance exif_subject_distance_range
548 exif_subject_location exif_tag_light_source exif_user_comment
549 exif_version exif_white_balance exif_x_resolution exif_y_resolution
550
551 =back
552
553 The following derived tags can also be set:
554
555 =over
556
557 exif_color_space_name exif_contrast_name exif_custom_rendered_name
558 exif_exposure_mode_name exif_exposure_program_name exif_flash_name
559 exif_focal_plane_resolution_unit_name exif_gain_control_name
560 exif_light_source_name exif_metering_mode_name
561 exif_resolution_unit_name exif_saturation_name
562 exif_scene_capture_type_name exif_sensing_method_name
563 exif_sharpness_name exif_subject_distance_range_name
564 exif_white_balance_name
565
566 =back
567
568 The derived tags are for enumerated fields, when the value for the
569 base field is valid then the text that appears in the EXIF
570 specification for that value appears in the derived field.  So for
571 example if C<exf_metering_mode> is C<5> then
572 C<exif_metering_mode_name> is set to C<Pattern>.
573
574 eg.
575
576   my $image = Imager->new;
577   $image->read(file => 'exiftest.jpg')
578     or die "Cannot load image: ", $image->errstr;
579   print $image->tags(name => "exif_image_description"), "\n";
580   print $image->tags(name => "exif_exposure_mode"), "\n";
581   print $image->tags(name => "exif_exposure_mode_name"), "\n";
582
583   # for the exiftest.jpg in the Imager distribution the output would be:
584   Imager Development Notes
585   0
586   Auto exposure
587
588 =for stopwords IPTC
589
590 =over
591
592 =item parseiptc()
593
594 Historically, Imager saves IPTC data when reading a JPEG image, the
595 parseiptc() method returns a list of key/value pairs resulting from a
596 simple decoding of that data.
597
598 Any future IPTC data decoding is likely to go into tags.
599
600 =back
601
602 =head2 GIF (Graphics Interchange Format)
603
604 When writing one of more GIF images you can use the same
605 L<Quantization Options|Imager::ImageTypes> as you can when converting
606 an RGB image into a paletted image.
607
608 When reading a GIF all of the sub-images are combined using the screen
609 size and image positions into one big image, producing an RGB image.
610 This may change in the future to produce a paletted image where possible.
611
612 When you read a single GIF with C<$img-E<gt>read()> you can supply a
613 reference to a scalar in the C<colors> parameter, if the image is read
614 the scalar will be filled with a reference to an anonymous array of
615 L<Imager::Color> objects, representing the palette of the image.  This
616 will be the first palette found in the image.  If you want the
617 palettes for each of the images in the file, use C<read_multi()> and
618 use the C<getcolors()> method on each image.
619
620 GIF does not support the spatial resolution tags.
621
622 Imager will set the following tags in each image when reading, and can
623 use most of them when writing to GIF:
624
625 =over
626
627 =item *
628
629 gif_left - the offset of the image from the left of the "screen"
630 ("Image Left Position")
631
632 =item *
633
634 gif_top - the offset of the image from the top of the "screen" ("Image
635 Top Position")
636
637 =item *
638
639 gif_interlace - non-zero if the image was interlaced ("Interlace
640 Flag")
641
642 =item *
643
644 gif_screen_width, gif_screen_height - the size of the logical
645 screen. When writing this is used as the minimum.  If any image being
646 written would extend beyond this then the screen size is extended.
647 ("Logical Screen Width", "Logical Screen Height").
648
649 =item *
650
651 gif_local_map - Non-zero if this image had a local color map.  If set
652 for an image when writing the image is quantized separately from the
653 other images in the file.
654
655 =item *
656
657 gif_background - The index in the global color map of the logical
658 screen's background color.  This is only set if the current image uses
659 the global color map.  You can set this on write too, but for it to
660 choose the color you want, you will need to supply only paletted
661 images and set the C<gif_eliminate_unused> tag to 0.
662
663 =item *
664
665 gif_trans_index - The index of the color in the color map used for
666 transparency.  If the image has a transparency then it is returned as
667 a 4 channel image with the alpha set to zero in this palette entry.
668 This value is not used when writing. ("Transparent Color Index")
669
670 =item *
671
672 gif_trans_color - A reference to an Imager::Color object, which is the
673 color to use for the palette entry used to represent transparency in
674 the palette.  You need to set the C<transp> option (see L<Quantization
675 options>) for this value to be used.
676
677 =item *
678
679 gif_delay - The delay until the next frame is displayed, in 1/100 of a
680 second.  ("Delay Time").
681
682 =item *
683
684 gif_user_input - whether or not a user input is expected before
685 continuing (view dependent) ("User Input Flag").
686
687 =item *
688
689 gif_disposal - how the next frame is displayed ("Disposal Method")
690
691 =item *
692
693 gif_loop - the number of loops from the Netscape Loop extension.  This
694 may be zero to loop forever.
695
696 =item *
697
698 gif_comment - the first block of the first GIF comment before each
699 image.
700
701 =item *
702
703 gif_eliminate_unused - If this is true, when you write a paletted
704 image any unused colors will be eliminated from its palette.  This is
705 set by default.
706
707 =item *
708
709 gif_colormap_size - the original size of the color map for the image.
710 The color map of the image may have been expanded to include out of
711 range color indexes.
712
713 =back
714
715 Where applicable, the ("name") is the name of that field from the C<GIF89>
716 standard.
717
718 The following GIF writing options are obsolete, you should set the
719 corresponding tag in the image, either by using the tags functions, or
720 by supplying the tag and value as options.
721
722 =over
723
724 =item *
725
726 gif_each_palette - Each image in the GIF file has it's own palette if
727 this is non-zero.  All but the first image has a local color table
728 (the first uses the global color table.
729
730 Use C<gif_local_map> in new code.
731
732 =item *
733
734 interlace - The images are written interlaced if this is non-zero.
735
736 Use C<gif_interlace> in new code.
737
738 =item *
739
740 gif_delays - A reference to an array containing the delays between
741 images, in 1/100 seconds.
742
743 Use C<gif_delay> in new code.
744
745 =item *
746
747 gif_positions - A reference to an array of references to arrays which
748 represent screen positions for each image.
749
750 New code should use the C<gif_left> and C<gif_top> tags.
751
752 =item *
753
754 gif_loop_count - If this is non-zero the Netscape loop extension block
755 is generated, which makes the animation of the images repeat.
756
757 This is currently unimplemented due to some limitations in C<giflib>.
758
759 =back
760
761 You can supply a C<page> parameter to the C<read()> method to read
762 some page other than the first.  The page is 0 based:
763
764   # read the second image in the file
765   $image->read(file=>"example.gif", page=>1)
766     or die "Cannot read second page: ",$image->errstr,"\n";
767
768 Before release 0.46, Imager would read multiple image GIF image files
769 into a single image, overlaying each of the images onto the virtual
770 GIF screen.
771
772 As of 0.46 the default is to read the first image from the file, as if
773 called with C<< page => 0 >>.
774
775 You can return to the previous behavior by calling read with the
776 C<gif_consolidate> parameter set to a true value:
777
778   $img->read(file=>$some_gif_file, gif_consolidate=>1);
779
780 As with the to_paletted() method, if you supply a colors parameter as
781 a reference to an array, this will be filled with Imager::Color
782 objects of the color table generated for the image file.
783
784 =head2 TIFF (Tagged Image File Format)
785
786 Imager can write images to either paletted or RGB TIFF images,
787 depending on the type of the source image.
788
789 When writing direct color images to TIFF the sample size of the
790 output file depends on the input:
791
792 =over
793
794 =item *
795
796 double/sample - written as 32-bit/sample TIFF
797
798 =item *
799
800 16-bit/sample - written as 16-bit/sample TIFF
801
802 =item *
803
804 8-bit/sample - written as 8-bit/sample TIFF
805
806 =back
807
808 For paletted images:
809
810 =over
811
812 =item *
813
814 C<< $img->is_bilevel >> is true - the image is written as bi-level
815
816 =item *
817
818 otherwise - image is written as paletted.
819
820 =back
821
822 If you are creating images for faxing you can set the I<class>
823 parameter set to C<fax>.  By default the image is written in fine
824 mode, but this can be overridden by setting the I<fax_fine> parameter
825 to zero.  Since a fax image is bi-level, Imager uses a threshold to
826 decide if a given pixel is black or white, based on a single channel.
827 For gray scale images channel 0 is used, for color images channel 1
828 (green) is used.  If you want more control over the conversion you can
829 use $img->to_paletted() to product a bi-level image.  This way you can
830 use dithering:
831
832   my $bilevel = $img->to_paletted(make_colors => 'mono',
833                                   translate => 'errdiff',
834                                   errdiff => 'stucki');
835
836 =over
837
838 =item *
839
840 C<class> - If set to 'fax' the image will be written as a bi-level fax
841 image.
842
843 =item *
844
845 C<fax_fine> - By default when C<class> is set to 'fax' the image is
846 written in fine mode, you can select normal mode by setting
847 C<fax_fine> to 0.
848
849 =back
850
851 Imager should be able to read any TIFF image you supply.  Paletted
852 TIFF images are read as paletted Imager images, since paletted TIFF
853 images have 16-bits/sample (48-bits/color) this means the bottom
854 8-bits are lost, but this shouldn't be a big deal.
855
856 TIFF supports the spatial resolution tags.  See the
857 C<tiff_resolutionunit> tag for some extra options.
858
859 As of Imager 0.62 Imager reads:
860
861 =over
862
863 =item *
864
865 8-bit/sample gray, RGB or CMYK images, including a possible alpha
866 channel as an 8-bit/sample image.
867
868 =item *
869
870 16-bit gray, RGB, or CMYK image, including a possible alpha channel as
871 a 16-bit/sample image.
872
873 =item *
874
875 32-bit gray, RGB image, including a possible alpha channel as a
876 double/sample image.
877
878 =item *
879
880 bi-level images as paletted images containing only black and white,
881 which other formats will also write as bi-level.
882
883 =item *
884
885 tiled paletted images are now handled correctly
886
887 =item *
888
889 other images are read using C<tifflib>'s RGBA interface as
890 8-bit/sample images.
891
892 =back
893
894 The following tags are set in a TIFF image when read, and can be set
895 to control output:
896
897 =over
898
899 =item *
900
901 C<tiff_compression> - When reading an image this is set to the numeric
902 value of the TIFF compression tag.
903
904 On writing you can set this to either a numeric compression tag value,
905 or one of the following values:
906
907   Ident     Number  Description
908   none         1    No compression
909   packbits   32773  Macintosh RLE
910   ccittrle     2    CCITT RLE
911   fax3         3    CCITT Group 3 fax encoding (T.4)
912   t4           3    As above
913   fax4         4    CCITT Group 4 fax encoding (T.6)
914   t6           4    As above
915   lzw          5    LZW
916   jpeg         7    JPEG
917   zip          8    Deflate (GZIP) Non-standard
918   deflate      8    As above.
919   oldzip     32946  Deflate with an older code.
920   ccittrlew  32771  Word aligned CCITT RLE
921
922 In general a compression setting will be ignored where it doesn't make
923 sense, eg. C<jpeg> will be ignored for compression if the image is
924 being written as bilevel.
925
926 =for stopwords LZW
927
928 Imager attempts to check that your build of C<libtiff> supports the
929 given compression, and will fallback to C<packbits> if it isn't
930 enabled.  eg. older distributions didn't include LZW compression, and
931 JPEG compression is only available if C<libtiff> is configured with
932 C<libjpeg>'s location.
933
934   $im->write(file => 'foo.tif', tiff_compression => 'lzw')
935     or die $im->errstr;
936
937 =item *
938
939 C<tags, tiff_jpegquality>C<tiff_jpegquality> - If C<tiff_compression>
940 is C<jpeg> then this can be a number from 1 to 100 giving the JPEG
941 compression quality.  High values are better quality and larger files.
942
943 =item *
944
945 X<tags, tiff_resolutionunit>C<tiff_resolutionunit> - The value of the
946 C<ResolutionUnit> tag.  This is ignored on writing if the
947 i_aspect_only tag is non-zero.
948
949 The C<i_xres> and C<i_yres> tags are expressed in pixels per inch no
950 matter the value of this tag, they will be converted to/from the value
951 stored in the TIFF file.
952
953 =item *
954
955 X<tags, tiff_resolutionunit_name>C<tiff_resolutionunit_name> - This is
956 set when reading a TIFF file to the name of the unit given by
957 C<tiff_resolutionunit>.  Possible results include C<inch>,
958 C<centimeter>, C<none> (the C<i_aspect_only> tag is also set reading
959 these files) or C<unknown>.
960
961 =item *
962
963 X<tags, tiff_bitspersample>C<tiff_bitspersample> - Bits per sample
964 from the image.  This value is not used when writing an image, it is
965 only set on a read image.
966
967 =item *
968
969 X<tags, tiff_photometric>C<tiff_photometric> - Value of the
970 C<PhotometricInterpretation> tag from the image.  This value is not
971 used when writing an image, it is only set on a read image.
972
973 =item *
974
975 C<tiff_documentname>, C<tiff_imagedescription>, C<tiff_make>,
976 C<tiff_model>, C<tiff_pagename>, C<tiff_software>, C<tiff_datetime>,
977 C<tiff_artist>, C<tiff_hostcomputer> - Various strings describing the
978 image.  C<tiff_datetime> must be formatted as "YYYY:MM:DD HH:MM:SS".
979 These correspond directly to the mixed case names in the TIFF
980 specification.  These are set in images read from a TIFF and saved
981 when writing a TIFF image.
982
983 =back
984
985 You can supply a C<page> parameter to the C<read()> method to read
986 some page other than the first.  The page is 0 based:
987
988   # read the second image in the file
989   $image->read(file=>"example.tif", page=>1)
990     or die "Cannot read second page: ",$image->errstr,"\n";
991
992 If you read an image with multiple alpha channels, then only the first
993 alpha channel will be read.
994
995 =head2 BMP (Windows Bitmap)
996
997 Imager can write 24-bit RGB, and 8, 4 and 1-bit per pixel paletted
998 Windows BMP files.  Currently you cannot write compressed BMP files
999 with Imager.
1000
1001 Imager can read 24-bit RGB, and 8, 4 and 1-bit perl pixel paletted
1002 Windows BMP files.  There is some support for reading 16-bit per pixel
1003 images, but I haven't found any for testing.
1004
1005 BMP has no support for multiple image files.
1006
1007 BMP files support the spatial resolution tags, but since BMP has no
1008 support for storing only an aspect ratio, if C<i_aspect_only> is set
1009 when you write the C<i_xres> and C<i_yres> values are scaled so the
1010 smaller is 72 DPI.
1011
1012 The following tags are set when you read an image from a BMP file:
1013
1014 =over
1015
1016 =item bmp_compression
1017
1018 The type of compression, if any.  This can be any of the following
1019 values:
1020
1021 =for stopwords RLE
1022
1023 =over
1024
1025 =item BI_RGB (0)
1026
1027 Uncompressed.
1028
1029 =item BI_RLE8 (1)
1030
1031 8-bits/pixel paletted value RLE compression.
1032
1033 =item BI_RLE4 (2)
1034
1035 4-bits/pixel paletted value RLE compression.
1036
1037 =item BI_BITFIELDS (3)
1038
1039 Packed RGB values.
1040
1041 =back
1042
1043 =item bmp_compression_name
1044
1045 The bmp_compression value as a BI_* string
1046
1047 =item bmp_important_colors
1048
1049 The number of important colors as defined by the writer of the image.
1050
1051 =item bmp_used_colors
1052
1053 Number of color used from the BMP header
1054
1055 =item bmp_filesize
1056
1057 The file size from the BMP header
1058
1059 =item bmp_bit_count
1060
1061 Number of bits stored per pixel. (24, 8, 4 or 1)
1062
1063 =back
1064
1065 =for stopwords Targa
1066
1067 =head2 TGA (Targa)
1068
1069 When storing Targa images RLE compression can be activated with the
1070 C<compress> parameter, the C<idstring> parameter can be used to set the
1071 Targa comment field and the C<wierdpack> option can be used to use the
1072 15 and 16 bit Targa formats for RGB and RGBA data.  The 15 bit format
1073 has 5 of each red, green and blue.  The 16 bit format in addition
1074 allows 1 bit of alpha.  The most significant bits are used for each
1075 channel.
1076
1077 Tags:
1078
1079 =over
1080
1081 =item tga_idstring
1082
1083 =item tga_bitspp
1084
1085 =item compressed
1086
1087 =back
1088
1089 =head2 RAW
1090
1091 When reading raw images you need to supply the width and height of the
1092 image in the C<xsize> and C<ysize> options:
1093
1094   $img->read(file=>'foo.raw', xsize=>100, ysize=>100)
1095     or die "Cannot read raw image\n";
1096
1097 If your input file has more channels than you want, or (as is common),
1098 junk in the fourth channel, you can use the C<datachannels> and
1099 C<storechannels> options to control the number of channels in your input
1100 file and the resulting channels in your image.  For example, if your
1101 input image uses 32-bits per pixel with red, green, blue and junk
1102 values for each pixel you could do:
1103
1104   $img->read(file=>'foo.raw', xsize=>100, ysize=>100, datachannels=>4,
1105              storechannels=>3)
1106     or die "Cannot read raw image\n";
1107
1108 Read parameters:
1109
1110 =over
1111
1112 =item *
1113
1114 raw_interleave - controls the ordering of samples within the image.
1115 Default: 1.  Alternatively and historically spelled C<interleave>.
1116 Possible values:
1117
1118 =over
1119
1120 =item *
1121
1122 0 - samples are pixel by pixel, so all samples for the first pixel,
1123 then all samples for the second pixel and so on.  eg. for a four pixel
1124 scan line the channels would be laid out as:
1125
1126   012012012012
1127
1128 =item *
1129
1130 1 - samples are line by line, so channel 0 for the entire scan line is
1131 followed by channel 1 for the entire scan line and so on.  eg. for a
1132 four pixel scan line the channels would be laid out as:
1133
1134   000011112222
1135
1136 This is the default.
1137
1138 =back
1139
1140 Unfortunately, historically, the default C<raw_interleave> for read
1141 has been 1, while writing only supports the C<raw_interleave> = 0
1142 format.
1143
1144 For future compatibility, you should always supply the
1145 C<raw_interleave> (or C<interleave>) parameter.  As of 0.68, Imager
1146 will warn if you attempt to read a raw image without a
1147 C<raw_interleave> parameter.
1148
1149 =item *
1150
1151 raw_storechannels - the number of channels to store in the image.
1152 Range: 1 to 4.  Default: 3.  Alternatively and historically spelled
1153 C<storechannels>.
1154
1155 =item *
1156
1157 raw_datachannels - the number of channels to read from the file.
1158 Range: 1 or more.  Default: 3.  Alternatively and historically spelled
1159 C<datachannels>.
1160
1161 =back
1162
1163   $img->read(file=>'foo.raw', xsize=100, ysize=>100, raw_interleave=>1)
1164     or die "Cannot read raw image\n";
1165
1166 =head2 PNG
1167
1168 There are no PNG specific tags.
1169
1170 =head2 ICO (Microsoft Windows Icon) and CUR (Microsoft Windows Cursor)
1171
1172 Icon and Cursor files are very similar, the only differences being a
1173 number in the header and the storage of the cursor hot spot.  I've
1174 treated them separately so that you're not messing with tags to
1175 distinguish between them.
1176
1177 The following tags are set when reading an icon image and are used
1178 when writing it:
1179
1180 =over
1181
1182 =item ico_mask
1183
1184 This is the AND mask of the icon.  When used as an icon in Windows 1
1185 bits in the mask correspond to pixels that are modified by the source
1186 image rather than simply replaced by the source image.
1187
1188 Rather than requiring a binary bitmap this is accepted in a specific format:
1189
1190 =over
1191
1192 =item *
1193
1194 first line consisting of the 0 placeholder, the 1 placeholder and a
1195 newline.
1196
1197 =item *
1198
1199 following lines which contain 0 and 1 placeholders for each scan line
1200 of the image, starting from the top of the image.
1201
1202 =back
1203
1204 When reading an image, '.' is used as the 0 placeholder and '*' as the
1205 1 placeholder.  An example:
1206
1207   .*
1208   ..........................******
1209   ..........................******
1210   ..........................******
1211   ..........................******
1212   ...........................*****
1213   ............................****
1214   ............................****
1215   .............................***
1216   .............................***
1217   .............................***
1218   .............................***
1219   ..............................**
1220   ..............................**
1221   ...............................*
1222   ...............................*
1223   ................................
1224   ................................
1225   ................................
1226   ................................
1227   ................................
1228   ................................
1229   *...............................
1230   **..............................
1231   **..............................
1232   ***.............................
1233   ***.............................
1234   ****............................
1235   ****............................
1236   *****...........................
1237   *****...........................
1238   *****...........................
1239   *****...........................
1240
1241 =back
1242
1243 The following tags are set when reading an icon:
1244
1245 =over
1246
1247 =item ico_bits
1248
1249 The number of bits per pixel used to store the image.
1250
1251 =back
1252
1253 For cursor files the following tags are set and read when reading and
1254 writing:
1255
1256 =over
1257
1258 =item cur_mask
1259
1260 This is the same as the ico_mask above.
1261
1262 =item cur_hotspotx
1263
1264 =item cur_hotspoty
1265
1266 The "hot" spot of the cursor image.  This is the spot on the cursor
1267 that you click with.  If you set these to out of range values they are
1268 clipped to the size of the image when written to the file.
1269
1270 =back
1271
1272 The following parameters can be supplied to read() or read_multi() to
1273 control reading of ICO/CUR files:
1274
1275 =over
1276
1277 =item *
1278
1279 ico_masked - if true, the default, then the icon/cursors mask is
1280 applied as an alpha channel to the image.  This may result in a
1281 paletted image being returned as a direct color image.  Default: 1
1282
1283   # retrieve the image as stored, without using the mask as an alpha
1284   # channel
1285   $img->read(file => 'foo.ico', ico_masked => 0)
1286     or die $img->errstr;
1287
1288 This was introduced in Imager 0.60.  Previously reading ICO images
1289 acted as if C<ico_masked =E<gt> 0>.
1290
1291 =back
1292
1293 C<cur_bits> is set when reading a cursor.
1294
1295 Examples:
1296
1297   my $img = Imager->new(xsize => 32, ysize => 32, channels => 4);
1298   $im->box(color => 'FF0000');
1299   $im->write(file => 'box.ico');
1300
1301   $im->settag(name => 'cur_hotspotx', value => 16);
1302   $im->settag(name => 'cur_hotspoty', value => 16);
1303   $im->write(file => 'box.cur');
1304
1305 =for stopwords BW
1306
1307 =head2 SGI (RGB, BW)
1308
1309 SGI images, often called by the extensions, RGB or BW, can be stored
1310 either uncompressed or compressed using an RLE compression.
1311
1312 By default, when saving to an extension of C<rgb>, C<bw>, C<sgi>,
1313 C<rgba> the file will be saved in SGI format.  The file extension is
1314 otherwise ignored, so saving a 3-channel image to a C<.bw> file will
1315 result in a 3-channel image on disk.
1316
1317 The following tags are set when reading a SGI image:
1318
1319 =over
1320
1321 =item *
1322
1323 i_comment - the C<IMAGENAME> field from the image.  Also written to
1324 the file when writing.
1325
1326 =item *
1327
1328 sgi_pixmin, sgi_pixmax - the C<PIXMIN> and C<PIXMAX> fields from the
1329 image.  On reading image data is expanded from this range to the full
1330 range of samples in the image.
1331
1332 =item *
1333
1334 sgi_bpc - the number of bytes per sample for the image.  Ignored when
1335 writing.
1336
1337 =item *
1338
1339 sgi_rle - whether or not the image is compressed.  If this is non-zero
1340 when writing the image will be compressed.
1341
1342 =back
1343
1344 =head1 ADDING NEW FORMATS
1345
1346 To support a new format for reading, call the register_reader() class
1347 method:
1348
1349 =over
1350
1351 =item register_reader
1352
1353 Registers single or multiple image read functions.
1354
1355 Parameters:
1356
1357 =over
1358
1359 =item *
1360
1361 type - the identifier of the file format, if Imager's
1362 i_test_format_probe() can identify the format then this value should
1363 match i_test_format_probe()'s result.
1364
1365 This parameter is required.
1366
1367 =item *
1368
1369 single - a code ref to read a single image from a file.  This is
1370 supplied:
1371
1372 =over
1373
1374 =item *
1375
1376 the object that read() was called on,
1377
1378 =item *
1379
1380 an Imager::IO object that should be used to read the file, and
1381
1382 =item *
1383
1384 all the parameters supplied to the read() method.
1385
1386 =back
1387
1388 The single parameter is required.
1389
1390 =item *
1391
1392 multiple - a code ref which is called to read multiple images from a
1393 file. This is supplied:
1394
1395 =over
1396
1397 =item *
1398
1399 an Imager::IO object that should be used to read the file, and
1400
1401 =item *
1402
1403 all the parameters supplied to the read_multi() method.
1404
1405 =back
1406
1407 =back
1408
1409 Example:
1410
1411   # from Imager::File::ICO
1412   Imager->register_reader
1413     (
1414      type=>'ico',
1415      single => 
1416      sub { 
1417        my ($im, $io, %hsh) = @_;
1418        $im->{IMG} = i_readico_single($io, $hsh{page} || 0);
1419
1420        unless ($im->{IMG}) {
1421          $im->_set_error(Imager->_error_as_msg);
1422          return;
1423        }
1424        return $im;
1425      },
1426      multiple =>
1427      sub {
1428        my ($io, %hsh) = @_;
1429      
1430        my @imgs = i_readico_multi($io);
1431        unless (@imgs) {
1432          Imager->_set_error(Imager->_error_as_msg);
1433          return;
1434        }
1435        return map { 
1436          bless { IMG => $_, DEBUG => $Imager::DEBUG, ERRSTR => undef }, 'Imager'
1437        } @imgs;
1438      },
1439     );
1440
1441 =item register_writer
1442
1443 Registers single or multiple image write functions.
1444
1445 Parameters:
1446
1447 =over
1448
1449 =item *
1450
1451 type - the identifier of the file format.  This is typically the
1452 extension in lowercase.
1453
1454 This parameter is required.
1455
1456 =item *
1457
1458 single - a code ref to write a single image to a file.  This is
1459 supplied:
1460
1461 =over
1462
1463 =item *
1464
1465 the object that write() was called on,
1466
1467 =item *
1468
1469 an Imager::IO object that should be used to write the file, and
1470
1471 =item *
1472
1473 all the parameters supplied to the write() method.
1474
1475 =back
1476
1477 The single parameter is required.
1478
1479 =item *
1480
1481 multiple - a code ref which is called to write multiple images to a
1482 file. This is supplied:
1483
1484 =over
1485
1486 =item *
1487
1488 the class name write_multi() was called on, this is typically
1489 C<Imager>.
1490
1491 =item *
1492
1493 an Imager::IO object that should be used to write the file, and
1494
1495 =item *
1496
1497 all the parameters supplied to the read_multi() method.
1498
1499 =back
1500
1501 =back
1502
1503 =back
1504
1505 If you name the reader module C<Imager::File::>I<your-format-name>
1506 where I<your-format-name> is a fully upper case version of the type
1507 value you would pass to read(), read_multi(), write() or write_multi()
1508 then Imager will attempt to load that module if it has no other way to
1509 read or write that format.
1510
1511 For example, if you create a module Imager::File::GIF and the user has
1512 built Imager without it's normal GIF support then an attempt to read a
1513 GIF image will attempt to load Imager::File::GIF.
1514
1515 If your module can only handle reading then you can name your module
1516 C<Imager::File::>I<your-format-name>C<Reader> and Imager will attempt
1517 to autoload it.
1518
1519 If your module can only handle writing then you can name your module 
1520 C<Imager::File::>I<your-format-name>C<Writer> and Imager will attempt
1521 to autoload it.
1522
1523 =head1 EXAMPLES
1524
1525 =head2 Producing an image from a CGI script
1526
1527 Once you have an image the basic mechanism is:
1528
1529 =for stopwords STDOUT
1530
1531 =over
1532
1533 =item 1.
1534
1535 set STDOUT to autoflush
1536
1537 =item 2.
1538
1539 output a content-type header, and optionally a content-length header
1540
1541 =item 3.
1542
1543 put STDOUT into binmode
1544
1545 =item 4.
1546
1547 call write() with the C<fd> or C<fh> parameter.  You will need to
1548 provide the C<type> parameter since Imager can't use the extension to
1549 guess the file format you want.
1550
1551 =back
1552
1553   # write an image from a CGI script
1554   # using CGI.pm
1555   use CGI qw(:standard);
1556   $| = 1;
1557   binmode STDOUT;
1558   print header(-type=>'image/gif');
1559   $img->write(type=>'gif', fd=>fileno(STDOUT))
1560     or die $img->errstr;
1561
1562 If you want to send a content length you can send the output to a
1563 scalar to get the length:
1564
1565   my $data;
1566   $img->write(type=>'gif', data=>\$data)
1567     or die $img->errstr;
1568   binmode STDOUT;
1569   print header(-type=>'image/gif', -content_length=>length($data));
1570   print $data;
1571
1572 =head2 Writing an animated GIF
1573
1574 The basic idea is simple, just use write_multi():
1575
1576   my @imgs = ...;
1577   Imager->write_multi({ file=>$filename, type=>'gif' }, @imgs);
1578
1579 If your images are RGB images the default quantization mechanism will
1580 produce a very good result, but can take a long time to execute.  You
1581 could either use the standard web color map:
1582
1583   Imager->write_multi({ file=>$filename, 
1584                         type=>'gif',
1585                         make_colors=>'webmap' },
1586                       @imgs);
1587
1588 or use a median cut algorithm to built a fairly optimal color map:
1589
1590   Imager->write_multi({ file=>$filename,
1591                         type=>'gif',
1592                         make_colors=>'mediancut' },
1593                       @imgs);
1594
1595 By default all of the images will use the same global color map, which
1596 will produce a smaller image.  If your images have significant color
1597 differences, you may want to generate a new palette for each image:
1598
1599   Imager->write_multi({ file=>$filename,
1600                         type=>'gif',
1601                         make_colors=>'mediancut',
1602                         gif_local_map => 1 },
1603                       @imgs);
1604
1605 which will set the C<gif_local_map> tag in each image to 1.
1606 Alternatively, if you know only some images have different colors, you
1607 can set the tag just for those images:
1608
1609   $imgs[2]->settag(name=>'gif_local_map', value=>1);
1610   $imgs[4]->settag(name=>'gif_local_map', value=>1);
1611
1612 and call write_multi() without a C<gif_local_map> parameter, or supply
1613 an arrayref of values for the tag:
1614
1615   Imager->write_multi({ file=>$filename,
1616                         type=>'gif',
1617                         make_colors=>'mediancut',
1618                         gif_local_map => [ 0, 0, 1, 0, 1 ] },
1619                       @imgs);
1620
1621 Other useful parameters include C<gif_delay> to control the delay
1622 between frames and C<transp> to control transparency.
1623
1624 =head2 Reading tags after reading an image
1625
1626 This is pretty simple:
1627
1628   # print the author of a TIFF, if any
1629   my $img = Imager->new;
1630   $img->read(file=>$filename, type='tiff') or die $img->errstr;
1631   my $author = $img->tags(name=>'tiff_author');
1632   if (defined $author) {
1633     print "Author: $author\n";
1634   }
1635
1636 =head1 BUGS
1637
1638 When saving GIF images the program does NOT try to shave off extra
1639 colors if it is possible.  If you specify 128 colors and there are
1640 only 2 colors used - it will have a 128 color table anyway.
1641
1642 =head1 SEE ALSO
1643
1644 Imager(3)
1645
1646 =cut