]> git.imager.perl.org - imager.git/blob - lib/Imager/Files.pod
48e544092d0ab918ff81dee5e749648d7010138e
[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 =head1 DESCRIPTION
22
23 You can read and write a variety of images formats, assuming you have
24 the appropriate libraries, and images can be read or written to/from
25 files, file handles, file descriptors, scalars, or through callbacks.
26
27 To see which image formats Imager is compiled to support the following
28 code snippet is sufficient:
29
30   use Imager;
31   print join " ", keys %Imager::formats;
32
33 This will include some other information identifying libraries rather
34 than file formats.
35
36 Reading writing to and from files is simple, use the C<read()>
37 method to read an image:
38
39   my $img = Imager->new;
40   $img->read(file=>$filename, type=>$type)
41     or die "Cannot read $filename: ", $img->errstr;
42
43 and the C<write()> method to write an image:
44
45   $img->write(file=>$filename, type=>$type)
46     or die "Cannot write $filename: ", $img->errstr;
47
48 If you're reading from a format that supports multiple images per
49 file, use the C<read_multi()> method:
50
51   my @imgs = Imager->read_multi(file=>$filename, type=>$type)
52     or die "Cannot read $filename: ", Imager->errstr;
53
54 and if you want to write multiple images to a single file use the
55 C<write_multi()> method:
56
57   Imager->write_multi({ file=> $filename, type=>$type }, @images)
58     or die "Cannot write $filename: ", Imager->errstr;
59
60 If the I<filename> includes an extension that Imager recognizes, then
61 you don't need the I<type>, but you may want to provide one anyway.
62 See L</Guessing types> for information on controlling this
63 recognition.
64
65 The C<type> parameter is a lowercase representation of the file type,
66 and can be any of the following:
67
68   bmp   Windows BitMaP (BMP)
69   gif   Graphics Interchange Format (GIF)
70   jpeg  JPEG/JFIF
71   png   Portable Network Graphics (PNG)
72   pnm   Portable aNyMap (PNM)
73   raw   Raw
74   rgb   SGI .rgb files
75   tga   TARGA
76   tiff  Tagged Image File Format (TIFF)
77
78 When you read an image, Imager may set some tags, possibly including
79 information about the spatial resolution, textual information, and
80 animation information.  See L<Imager::ImageTypes/Tags> for specifics.
81
82 =head2 Input and output
83
84 When reading or writing you can specify one of a variety of sources or
85 targets:
86
87 =over
88
89 =item file
90
91 The C<file> parameter is the name of the image file to be written to
92 or read from.  If Imager recognizes the extension of the file you do
93 not need to supply a C<type>.
94
95 =item fh
96
97 C<fh> is a file handle, typically either returned from
98 C<<IO::File->new()>>, or a glob from an C<open> call.  You should call
99 C<binmode> on the handle before passing it to Imager.
100
101 Imager will set the handle to autoflush to make sure any buffered data
102 is flushed , since Imager will write to the file descriptor (from
103 fileno()) rather than writing at the perl level.
104
105 =item fd
106
107 C<fd> is a file descriptor.  You can get this by calling the
108 C<fileno()> function on a file handle, or by using one of the standard
109 file descriptor numbers.
110
111 If you get this from a perl file handle, you may need to flush any
112 buffered output, otherwise it may appear in the output stream after
113 the image.
114
115 =item data
116
117 When reading data, C<data> is a scalar containing the image file data,
118 when writing, C<data> is a reference to the scalar to save the image
119 file data too.  For GIF images you will need giflib 4 or higher, and
120 you may need to patch giflib to use this option for writing.
121
122 =item callback
123
124 Imager will make calls back to your supplied coderefs to read, write
125 and seek from/to/through the image file.
126
127 When reading from a file you can use either C<callback> or C<readcb>
128 to supply the read callback, and when writing C<callback> or
129 C<writecb> to supply the write callback.
130
131 When writing you can also supply the C<maxbuffer> option to set the
132 maximum amount of data that will be buffered before your write
133 callback is called.  Note: the amount of data supplied to your
134 callback can be smaller or larger than this size.
135
136 The read callback is called with 2 parameters, the minimum amount of
137 data required, and the maximum amount that Imager will store in it's C
138 level buffer.  You may want to return the minimum if you have a slow
139 data source, or the maximum if you have a fast source and want to
140 prevent many calls to your perl callback.  The read data should be
141 returned as a scalar.
142
143 Your write callback takes exactly one parameter, a scalar containing
144 the data to be written.  Return true for success.
145
146 The seek callback takes 2 parameters, a I<POSITION>, and a I<WHENCE>,
147 defined in the same way as perl's seek function.
148
149 You can also supply a C<closecb> which is called with no parameters
150 when there is no more data to be written.  This could be used to flush
151 buffered data.
152
153 =back
154
155 =head2 Guessing types
156
157 Imager uses the code reference in $Imager::FORMATGUESS to guess the
158 file type when you don't supply a C<type>.  The code reference is
159 called with a single parameter, the filename of the file.  The code
160 reference is only called if a C<file> parameter is supplied to the
161 file access method.
162
163 Return either a valid Imager file type, or undef.
164
165   # I'm writing jpegs to weird filenames
166   local $Imager::FORMATGUESS = sub { 'jpeg' };
167
168 =head1 TYPE SPECIFIC INFORMATION
169
170 The different image formats can write different image type, and some have
171 different options to control how the images are written.
172
173 When you call C<write()> or C<write_multi()> with an option that has
174 the same name as a tag for the image format you're writing, then the
175 value supplied to that option will be used to set the corresponding
176 tag in the image.  Depending on the image format, these values will be
177 used when writing the image.
178
179 This replaces the previous options that were used when writing GIF
180 images.  Currently if you use an obsolete option, it will be converted
181 to the equivalent tag and Imager will produced a warning.  You can
182 suppress these warnings by calling the C<Imager::init()> function with
183 the C<warn_obsolete> option set to false:
184
185   Imager::init(warn_obsolete=>0);
186
187 At some point in the future these obsolete options will no longer be
188 supported.
189
190 =head2 PNM (Portable aNy Map)
191
192 Imager can write PGM (Portable Gray Map) and PPM (Portable PixMaps)
193 files, depending on the number of channels in the image.  Currently
194 the images are written in binary formats.  Only 1 and 3 channel images
195 can be written, including 1 and 3 channel paletted images.
196
197   $img->write(file=>'foo.ppm') or die $img->errstr;
198
199 Imager can read both the ASCII and binary versions of each of the PBM
200 (Portable BitMap), PGM and PPM formats.
201
202   $img->read(file=>'foo.ppm') or die $img->errstr;
203
204 PNM does not support the spatial resolution tags.
205
206 =head2 JPEG
207
208 You can supply a C<jpegquality> parameter (0-100) when writing a JPEG
209 file, which defaults to 75%.  Only 1 and 3 channel images
210 can be written, including 1 and 3 channel paletted images.
211
212   $img->write(file=>'foo.jpg', jpegquality=>90) or die $img->errstr;
213
214 Imager will read a grayscale JPEG as a 1 channel image and a color
215 JPEG as a 3 channel image.
216
217   $img->read(file=>'foo.jpg') or die $img->errstr;
218
219 PNM does not support the spatial resolution tags.
220
221 =head2 GIF (Graphics Interchange Format)
222
223 When writing one of more GIF images you can use the same
224 L<Quantization Options|Imager::ImageTypes> as you can when converting
225 an RGB image into a paletted image.
226
227 When reading a GIF all of the sub-images are combined using the screen
228 size and image positions into one big image, producing an RGB image.
229 This may change in the future to produce a paletted image where possible.
230
231 When you read a single GIF with C<$img-E<gt>read()> you can supply a
232 reference to a scalar in the C<colors> parameter, if the image is read
233 the scalar will be filled with a reference to an anonymous array of
234 L<Imager::Color> objects, representing the palette of the image.  This
235 will be the first palette found in the image.  If you want the
236 palettes for each of the images in the file, use C<read_multi()> and
237 use the C<getcolors()> method on each image.
238
239 GIF does not support the spatial resolution tags.
240
241 Imager will set the following tags in each image when reading, and can
242 use most of them when writing to GIF:
243
244 =over
245
246 =item gif_left
247
248 the offset of the image from the left of the "screen" ("Image Left
249 Position")
250
251 =item gif_top
252
253 the offset of the image from the top of the "screen" ("Image Top Position")
254
255 =item gif_interlace
256
257 non-zero if the image was interlaced ("Interlace Flag")
258
259 =item gif_screen_width
260
261 =item gif_screen_height
262
263 the size of the logical screen. When writing this is used as the
264 minimum.  If any image being written would extend beyond this the
265 screen size is extended.  ("Logical Screen Width", "Logical Screen
266 Height").
267
268 When writing this is used as a minimum, if the combination of the
269 image size and the image's C<gif_left> and C<gif_top> is beyond this
270 size then the screen size will be expanded.
271
272 =item gif_local_map
273
274 Non-zero if this image had a local color map.  If set for an image
275 when writing the image is quantized separately from the other images
276 in the file.
277
278 =item gif_background
279
280 The index in the global colormap of the logical screen's background
281 color.  This is only set if the current image uses the global
282 colormap.  You can set this on write too, but for it to choose the
283 color you want, you will need to supply only paletted images and set
284 the C<gif_eliminate_unused> tag to 0.
285
286 =item gif_trans_index
287
288 The index of the color in the colormap used for transparency.  If the
289 image has a transparency then it is returned as a 4 channel image with
290 the alpha set to zero in this palette entry.  This value is not used
291 when writing. ("Transparent Color Index")
292
293 =item gif_trans_color
294
295 A reference to an Imager::Color object, which is the colour to use for
296 the palette entry used to represent transparency in the palette.  You
297 need to set the transp option (see L<Quantization options>) for this
298 value to be used.
299
300 =item gif_delay
301
302 The delay until the next frame is displayed, in 1/100 of a second. 
303 ("Delay Time").
304
305 =item gif_user_input
306
307 whether or not a user input is expected before continuing (view dependent) 
308 ("User Input Flag").
309
310 =item gif_disposal
311
312 how the next frame is displayed ("Disposal Method")
313
314 =item gif_loop
315
316 the number of loops from the Netscape Loop extension.  This may be zero.
317
318 =item gif_comment
319
320 the first block of the first gif comment before each image.
321
322 =item gif_eliminate_unused
323
324 If this is true, when you write a paletted image any unused colors
325 will be eliminated from its palette.  This is set by default.
326
327 =back
328
329 Where applicable, the ("name") is the name of that field from the GIF89 
330 standard.
331
332 The following gif writing options are obsolete, you should set the
333 corresponding tag in the image, either by using the tags functions, or
334 by supplying the tag and value as options.
335
336 =over
337
338 =item gif_each_palette
339
340 Each image in the gif file has it's own palette if this is non-zero.
341 All but the first image has a local colour table (the first uses the
342 global colour table.
343
344 Use C<gif_local_map> in new code.
345
346 =item interlace
347
348 The images are written interlaced if this is non-zero.
349
350 Use C<gif_interlace> in new code.
351
352 =item gif_delays
353
354 A reference to an array containing the delays between images, in 1/100
355 seconds.
356
357 Use C<gif_delay> in new code.
358
359 =item gif_positions
360
361 A reference to an array of references to arrays which represent screen
362 positions for each image.
363
364 New code should use the C<gif_left> and C<gif_top> tags.
365
366 =item gif_loop_count
367
368 If this is non-zero the Netscape loop extension block is generated,
369 which makes the animation of the images repeat.
370
371 This is currently unimplemented due to some limitations in giflib.
372
373 =back
374
375 =head2 TIFF (Tagged Image File Format)
376
377 Imager can write images to either paletted or RGB TIFF images,
378 depending on the type of the source image.  Currently if you write a
379 16-bit/sample or double/sample image it will be written as an
380 8-bit/sample image.  Only 1 or 3 channel images can be written.
381
382 If you are creating images for faxing you can set the I<class>
383 parameter set to C<fax>.  By default the image is written in fine
384 mode, but this can be overridden by setting the I<fax_fine> parameter
385 to zero.  Since a fax image is bi-level, Imager uses a threshold to
386 decide if a given pixel is black or white, based on a single channel.
387 For greyscale images channel 0 is used, for color images channel 1
388 (green) is used.  If you want more control over the conversion you can
389 use $img->to_paletted() to product a bi-level image.  This way you can
390 use dithering:
391
392   my $bilevel = $img->to_paletted(colors=>[ NC(0,0,0), NC(255,255,255) ],
393                                   make_colors => 'none',
394                                   translate => 'errdiff',
395                                   errdiff => 'stucki');
396
397 =over
398
399 =item class
400
401 If set to 'fax' the image will be written as a bi-level fax image.
402
403 =item fax_fine
404
405 By default when I<class> is set to 'fax' the image is written in fine
406 mode, you can select normal mode by setting I<fax_fine> to 0.
407
408 =back
409
410 Imager should be able to read any TIFF image you supply.  Paletted
411 TIFF images are read as paletted Imager images, since paletted TIFF
412 images have 16-bits/sample (48-bits/color) this means the bottom
413 8-bits are lost, but this shouldn't be a big deal.  Currently all
414 direct color images are read at 8-bits/sample.
415
416 TIFF supports the spatial resolution tags.  See the
417 C<tiff_resolutionunit> tag for some extra options.
418
419 The following tags are set in a TIFF image when read, and can be set
420 to control output:
421
422 =over
423
424 =item tiff_resolutionunit
425
426 The value of the ResolutionUnit tag.  This is ignored on writing if
427 the i_aspect_only tag is non-zero.
428
429 The C<i_xres> and C<i_yres> tags are expressed in pixels per inch no
430 matter tha value of this tag, they will be converted to/from the value
431 stored in the TIFF file.
432
433 =item tiff_documentname
434
435 =item tiff_imagedescription
436
437 =item tiff_make
438
439 =item tiff_model
440
441 =item tiff_pagename
442
443 =item tiff_software
444
445 =item tiff_datetime
446
447 =item tiff_artist
448
449 =item tiff_hostcomputer
450
451 Various strings describing the image.  tiff_datetime must be formatted
452 as "YYYY:MM:DD HH:MM:SS".  These correspond directly to the mixed case
453 names in the TIFF specification.  These are set in images read from a
454 TIFF and saved when writing a TIFF image.
455
456 =back
457
458 =head2 BMP (BitMaP)
459
460 Imager can write 24-bit RGB, and 8, 4 and 1-bit per pixel paletted
461 Windows BMP files.  Currently you cannot write compressed BMP files
462 with Imager.
463
464 Imager can read 24-bit RGB, and 8, 4 and 1-bit perl pixel paletted
465 Windows BMP files.  There is some support for reading 16-bit per pixel
466 images, but I haven't found any for testing.
467
468 BMP has no support for multi-image files.
469
470 BMP files support the spatial resolution tags, but since BMP has no
471 support for storing only an aspect ratio, if C<i_aspect_only> is set
472 when you write the C<i_xres> and C<i_yres> values are scaled so the
473 smaller it 72 DPI.
474
475 The following tags are set when you read an image from a BMP file:
476
477 =over
478
479 =item bmp_compression
480
481 The type of compression, if any.  This can be any of the following
482 values:
483
484 =over
485
486 =item BI_RGB (0)
487
488 Uncompressed.
489
490 =item BI_RLE8 (1)
491
492 8-bits/pixel paletted value RLE compression.
493
494 =item BI_RLE4 (2)
495
496 4-bits/pixel paletted value RLE compression.
497
498 =item BI_BITFIELDS (3)
499
500 Packed RGB values.
501
502 =back
503
504 =item bmp_important_colors
505
506 The number of important colors as defined by the writer of the image.
507
508 =back
509
510 =head2 TGA (TarGA)
511
512 When storing targa images rle compression can be activated with the
513 'compress' parameter, the 'idstring' parameter can be used to set the
514 targa comment field and the 'wierdpack' option can be used to use the
515 15 and 16 bit targa formats for rgb and rgba data.  The 15 bit format
516 has 5 of each red, green and blue.  The 16 bit format in addition
517 allows 1 bit of alpha.  The most significant bits are used for each
518 channel.
519
520
521 Tags:
522
523 =over
524
525 =item tga_idstring
526
527 =item tga_bitspp
528
529 =item compressed
530
531 =back
532
533
534 =head2 RAW
535
536
537 When reading raw images you need to supply the width and height of the
538 image in the xsize and ysize options:
539
540   $img->read(file=>'foo.raw', xsize=>100, ysize=>100)
541     or die "Cannot read raw image\n";
542
543 If your input file has more channels than you want, or (as is common),
544 junk in the fourth channel, you can use the datachannels and
545 storechannels options to control the number of channels in your input
546 file and the resulting channels in your image.  For example, if your
547 input image uses 32-bits per pixel with red, green, blue and junk
548 values for each pixel you could do:
549
550   $img->read(file=>'foo.raw', xsize=>100, ysize=>100, datachannels=>4,
551              storechannels=>3)
552     or die "Cannot read raw image\n";
553
554 Normally the raw image is expected to have the value for channel 1
555 immediately following channel 0 and channel 2 immediately following
556 channel 1 for each pixel.  If your input image has all the channel 0
557 values for the first line of the image, followed by all the channel 1
558 values for the first line and so on, you can use the interleave option:
559
560   $img->read(file=>'foo.raw', xsize=100, ysize=>100, interleave=>1)
561     or die "Cannot read raw image\n";
562
563 =head1 EXAMPLES
564
565 =head2 Producing an image from a CGI script
566
567 Once you have an image the basic mechanism is:
568
569 =over
570
571 =item 1.
572
573 set STDOUT to autoflush
574
575 =item 2.
576
577 output a content-type header, and optionally a content-length header
578
579 =item 3.
580
581 put STDOUT into binmode
582
583 =item 4.
584
585 call write() with the C<fd> or C<fh> parameter.  You will need to
586 provide the C<type> parameter since 
587
588 =back
589
590   # write an image from a CGI script
591   # using CGI.pm
592   use CGI qw(:standard);
593   $| = 1;
594   binmode STDOUT;
595   print header(-type=>'image/gif');
596   $img->write(type=>'gif', fd=>fileno(STDOUT))
597     or die $img->errstr;
598
599 If you want to send a content length you can send the output to a
600 scalar to get the length:
601
602   my $data;
603   $img->write(type=>'gif', data=>\$data)
604     or die $img->errstr;
605   binmode STDOUT;
606   print header(-type=>'image/gif', -content_length=>length($data));
607   print $data;
608
609 =head2 Writing an animated GIF
610
611 The basic idea is simple, just use write_multi():
612
613   my @imgs = ...;
614   Imager->write_multi({ file=>$filename, type=>'gif' }, @imgs);
615
616 If your images are RGB images the default quantization mechanism will
617 produce a very good result, but can take a long time to execute.  You
618 could either use the standard webmap:
619
620   Imager->write_multi({ file=>$filename, 
621                         type=>'gif',
622                         make_colors=>'webmap' },
623                       @imgs);
624
625 or use a median cut algorithm to built a fairly optimal color map:
626
627   Imager->write_multi({ file=>$filename,
628                         type=>'gif',
629                         make_colors=>'mediancut' },
630                       @imgs);
631
632 By default all of the images will use the same global colormap, which
633 will produce a smaller image.  If your images have significant color
634 differences, you may want to generate a new palette for each image:
635
636   Imager->write_multi({ file=>$filename,
637                         type=>'gif',
638                         make_colors=>'mediancut',
639                         gif_local_map => 1 },
640                       @imgs);
641
642 which will set the C<gif_local_map> tag in each image to 1.
643 Alternatively, if you know only some images have different colors, you
644 can set the tag just for those images:
645
646   $imgs[2]->settag(name=>'gif_local_map', value=>1);
647   $imgs[4]->settag(name=>'gif_local_map', value=>1);
648
649 and call write_multi() without a C<gif_local_map> parameter, or supply
650 an arrayref of values for the tag:
651
652   Imager->write_multi({ file=>$filename,
653                         type=>'gif',
654                         make_colors=>'mediancut',
655                         gif_local_map => [ 0, 0, 1, 0, 1 ] },
656                       @imgs);
657
658 Other useful parameters include C<gif_delay> to control the delay
659 between frames and C<transp> to control transparency.
660
661 =head2 Reading tags after reading an image
662
663 This is pretty simple:
664
665   # print the author of a TIFF, if any
666   my $img = Imager->new;
667   $img->read(file=>$filename, type='tiff') or die $img->errstr;
668   my $author = $img->tags(name=>'tiff_author');
669   if (defined $author) {
670     print "Author: $author\n";
671   }
672
673 =head1 BUGS
674
675 When saving Gif images the program does NOT try to shave of extra
676 colors if it is possible.  If you specify 128 colors and there are
677 only 2 colors used - it will have a 128 colortable anyway.
678
679 =head1 SEE ALSO
680
681 Imager(3)
682
683 =cut