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