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