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