File Coverage

lib/Image/Info.pm
Criterion Covered Total %
statement 92 104 88.4
branch 61 80 76.2
condition 7 11 63.6
subroutine 15 15 100.0
pod 5 5 100.0
total 180 215 83.7


line stmt bran cond sub pod time code
1              
2             #############################################################################
3             #
4             # ATTENTION! This file is autogenerated from dev/Info.pm.tmpl - DO NOT EDIT!
5             #
6             #############################################################################
7              
8             package Image::Info;
9              
10             # Copyright 1999-2004, Gisle Aas.
11             #
12             # This library is free software; you can redistribute it and/or
13             # modify it under the same terms as Perl v5.8.8 itself.
14             #
15             # Previously maintained by Tels - (c) 2006 - 2008.
16             # Currently maintained by Slaven Rezic - (c) 2008 - 2023.
17              
18 25     25   3875953 use strict;
  25         54  
  25         10001  
19              
20             our $VERSION = '1.45';
21              
22             require Exporter;
23             *import = \&Exporter::import;
24              
25             our @EXPORT_OK = qw(image_info dim html_dim image_type determine_file_format);
26              
27             # already required and failed sub-modules are remembered here
28             my %mod_failure;
29              
30             sub image_info
31             {
32 85     85 1 4539568 my $source = _source(shift);
33 85 100       349 return $source if ref $source eq 'HASH'; # Pass on errors
34              
35             # What sort of file is it?
36 84         239 my $head = _head($source);
37              
38 84 50       262 return $head if ref($head) eq 'HASH'; # error?
39              
40 84 50       240 my $format = determine_file_format($head)
41             or return { error => 'Unrecognized file format' };
42              
43 84         321 return _image_info_for_format($format, $source);
44             }
45              
46             # Note: this function is private, but may be used by Image::Info::*
47             # implementations (i.e. the WBMP implementation)
48             sub _image_info_for_format
49             {
50 85     85   219 my($format, $source) = @_;
51              
52 85         183 my $mod = "Image::Info::$format";
53 85         162 my $sub = "$mod\::process_file";
54 85         505 my $info = bless [], "Image::Info::Result";
55 85         165 eval {
56 85 100       396 unless (defined &$sub) {
57             # already required and failed?
58 34 50       170 if (my $fail = $mod_failure{$mod}) {
59 0         0 die $fail;
60             }
61 34         2535 eval "require $mod";
62 34 50       213 if ($@) {
63 0         0 $mod_failure{$mod} = $@;
64 0         0 die $@;
65             }
66 34 50       209 die "$mod did not define &$sub" unless defined &$sub;
67             }
68              
69 85         279 my %cnf = @_;
70             {
71             # call process_file()
72 25     25   798 no strict 'refs';
  25         44  
  25         46687  
  85         122  
73 85         349 &$sub($info, $source, \%cnf);
74             }
75 84         566 $info->clean_up;
76             };
77 85 100       290 return { error => $@ } if $@;
78 84 100       1710 return wantarray ? @$info : $info->[0];
79             }
80              
81             sub image_type
82             {
83 2     2 1 1903 my $source = _source(shift);
84 2 100       12 return $source if ref $source eq 'HASH'; # Pass on errors
85              
86             # What sort of file is it?
87 1 50       5 my $head = _head($source) or return _os_err("Can't read head");
88 1 50       3 my $format = determine_file_format($head)
89             or return { error => "Unrecognized file format" };
90              
91 1         21 return { file_type => $format };
92             }
93              
94             # Note: this function is private, but may be used by Image::Info::*
95             # implementations (i.e. the WBMP implementation)
96             sub _source
97             {
98 88     88   178 my $source = shift;
99 88 100       336 if (!ref $source) {
    50          
100 61         130 my $fh;
101 61 50       174 if ($] < 5.006) {
102 0         0 require Symbol;
103 0         0 $fh = Symbol::gensym();
104 0 0       0 open($fh, $source) || return _os_err("Can't open $source");
105             }
106             else {
107 61 100       4797 open $fh, '<', $source
108             or return _os_err("Can't open $source");
109             }
110 59         166 ${*$fh} = $source; # keep filename in case somebody wants to know
  59         281  
111 59         189 binmode($fh);
112 59         138 $source = $fh;
113             }
114             elsif (ref($source) eq "SCALAR") {
115             # Earlier PerlIO::scalar versions may segfault or consume lots
116             # of memory for some invalid images, see
117             # RT #100847 and img/segfault.tif
118 27 50 33     46 if (eval { require PerlIO::scalar; PerlIO::scalar->VERSION(0.21) } ||
  27         2060  
  27         676  
119 0         0 !eval { require IO::Scalar; 1 }) {
  0         0  
120 27 50       224 open(my $s, "<", $source) or return _os_err("Can't open string");
121 27         53 $source = $s;
122             }
123             else {
124 0         0 $source = IO::Scalar->new($source);
125             }
126             }
127             else {
128 0 0       0 seek($source, 0, 0) or return _os_err("Can't rewind");
129             }
130              
131 86         208 $source;
132             }
133              
134             sub _head
135             {
136 85     85   128 my $source = shift;
137 85         105 my $head;
138              
139             # Originally was 32 bytes.
140             # In the meantime lowered to 11 bytes.
141             # But XBM probably need more because of a leading comment.
142 85         133 my $to_read = 64;
143 85         3039 my $read = read($source, $head, $to_read);
144              
145 85 50       288 return _os_err("Couldn't read any bytes") if !$read;
146              
147 85 50       261 if (ref($source) eq "IO::String") {
148             # XXX workaround until we can trap seek() with a tied file handle
149 0         0 $source->setpos(0);
150             }
151             else {
152 85 50       636 seek($source, 0, 0) or return _os_err("Can't rewind");
153             }
154 85         213 $head;
155             }
156              
157             sub _os_err
158             {
159 2     2   38 return { error => "$_[0]: $!",
160             Errno => $!+0,
161             };
162             }
163              
164             sub determine_file_format
165             {
166 86     86 1 2078 local($_) = @_;
167 86 100       360 return "JPEG" if /^\xFF\xD8/;
168 65 100       185 return "PNG" if /^\x89PNG\x0d\x0a\x1a\x0a/;
169 57 100       208 return "GIF" if /^GIF8[79]a/;
170 48 100       138 return "TIFF" if /^MM\x00\x2a/;
171 47 100       159 return "TIFF" if /^II\x2a\x00/;
172 42 100       120 return "BMP" if /^BM/;
173 38 100       147 return "ICO" if /^\000\000\001\000/;
174 35 100       148 return "PPM" if /^P[1-6]/;
175 26 100       358 return "XPM" if /(^\/\* XPM \*\/)|(static\s+char\s+\*\w+\[\]\s*=\s*{\s*"\d+)/;
176 23 100       98 return "XBM" if /^(?:\/\*.*\*\/\n)?#define\s/;
177 18 100       69 return "AVIF" if /\A....ftypavif/s;
178 15 100       80 return "SVG" if /^(<\?xml|[\012\015\t ]*<svg\b)/;
179 10 50       73 return "WEBP" if /^RIFF.{4}WEBP/s;
180 0         0 return undef;
181             }
182              
183             sub dim
184             {
185 18   50 18 1 43981 my $img = shift || return;
186 18   100     80 my $x = $img->{width} || return;
187 17   50     62 my $y = $img->{height} || return;
188 17 100       110 wantarray ? ($x, $y) : "${x}x$y";
189             }
190              
191             sub html_dim
192             {
193 2     2 1 6 my($x, $y) = dim(@_);
194 2 100       11 return "" unless $x;
195 1         6 "width=\"$x\" height=\"$y\"";
196             }
197              
198             #############################################################################
199             package Image::Info::Result;
200              
201             sub push_info
202             {
203 2135     2135   3783 my($self, $n, $key) = splice(@_, 0, 3);
204 2135         2122 push(@{$self->[$n]{$key}}, @_);
  2135         6994  
205             }
206              
207             sub replace_info
208             {
209 85     85   133 my($self, $n, $key) = splice(@_, 0, 3);
210 85         225 $self->[$n]{$key}[0] = $_[0];
211             }
212              
213             sub clean_up
214             {
215 84     84   134 my $self = shift;
216 84         201 for (@$self) {
217 108         510 for my $k (keys %$_) {
218 1875         2111 my $a = $_->{$k};
219 1875 100       3933 $_->{$k} = $a->[0] if @$a <= 1;
220             }
221             }
222             }
223              
224             sub get_info {
225 217     217   355 my($self, $n, $key, $delete) = @_;
226 217 100       422 my $v = $delete ? delete $self->[$n]{$key} : $self->[$n]{$key};
227 217   100     523 $v ||= [];
228 217         619 @$v;
229             }
230              
231             1;
232              
233             __END__
234              
235             =head1 NAME
236              
237             Image::Info - Extract meta information from image files
238              
239             =head1 SYNOPSIS
240              
241             use Image::Info qw(image_info dim);
242              
243             my $info = image_info("image.jpg");
244             if (my $error = $info->{error}) {
245             die "Can't parse image info: $error\n";
246             }
247             my $color = $info->{color_type};
248            
249             my $type = image_type("image.jpg");
250             if (my $error = $type->{error}) {
251             die "Can't determine file type: $error\n";
252             }
253             die "No gif files allowed!" if $type->{file_type} eq 'GIF';
254            
255             my($w, $h) = dim($info);
256              
257             =head1 DESCRIPTION
258              
259             This module provides functions to extract various kinds of meta
260             information from image files.
261              
262             =head2 EXPORTS
263              
264             Exports nothing by default, but can export the following methods
265             on request:
266              
267             image_info
268             image_type
269             dim
270             html_dim
271             determine_file_type
272              
273             =head2 METHODS
274              
275             The following functions are provided by the C<Image::Info> module:
276              
277             =over
278              
279             =item image_info( $file )
280              
281             =item image_info( \$imgdata )
282              
283             =item image_info( $file, key => value,... )
284              
285             This function takes the name of a file or a file handle as argument
286             and will return one or more hashes (actually hash references)
287             describing the images inside the file. If there is only one image in
288             the file only one hash is returned. In scalar context, only the hash
289             for the first image is returned.
290              
291             In case of error, a hash containing the "error" key will be
292             returned. The corresponding value will be an appropriate error
293             message.
294              
295             If a reference to a scalar is passed as an argument to this function,
296             then it is assumed that this scalar contains the raw image data
297             directly.
298              
299             The C<image_info()> function also take optional key/value style arguments
300             that can influence what information is returned.
301              
302             =item image_type( $file )
303              
304             =item image_type( \$imgdata )
305              
306             Returns a hash with only one key, C<< file_type >>. The value
307             will be the type of the file. On error, sets the two keys
308             C<< error >> and C<< Errno >>.
309              
310             This function is a dramatically faster alternative to the image_info
311             function for situations in which you B<only> need to find the image type.
312              
313             It uses only the internal file-type detection to do this, and thus does
314             not need to load any of the image type-specific driver modules, and does
315             not access to entire file. It also only needs access to the first 11
316             bytes of the file.
317              
318             To maintain some level of compatibility with image_info, image_type
319             returns in the same format, with the same error message style. That is,
320             it returns a HASH reference, with the C<< $type->{error} >> key set if
321             there was an error.
322              
323             On success, the HASH reference will contain the single key C<< file_type >>,
324             which represents the type of the file, expressed as the type code used for
325             the various drivers ('GIF', 'JPEG', 'TIFF' and so on).
326              
327             If there are multiple images within the file they will be ignored, as this
328             function provides only the type of the overall file, not of the various
329             images within it. This function will not return multiple hashes if the file
330             contains multiple images.
331              
332             Of course, in all (or at least effectively all) cases the type of the images
333             inside the file is going to be the same as that of the file itself.
334              
335             =item dim( $info_hash )
336              
337             Takes an hash as returned from C<image_info()> and returns the dimensions
338             ($width, $height) of the image. In scalar context returns the
339             dimensions as a string.
340              
341             =item html_dim( $info_hash )
342              
343             Returns the dimensions as a string suitable for embedding directly
344             into HTML or SVG <img>-tags. E.g.:
345              
346             print "<img src="..." @{[html_dim($info)]}>\n";
347              
348             =item determine_file_format( $filedata )
349              
350             Determines the file format from the passed file data (a normal Perl
351             scalar containing the first bytes of the file), and returns
352             either undef for an unknown file format, or a string describing
353             the format, like "BMP" or "JPEG".
354              
355             =back
356              
357             =head1 Image descriptions
358              
359             The C<image_info()> function returns meta information about each image in
360             the form of a reference to a hash. The hash keys used are in most
361             cases based on the TIFF element names. All lower case keys are
362             mandatory for all file formats and will always be there unless an
363             error occurred (in which case the "error" key will be present.) Mixed
364             case keys will only be present when the corresponding information
365             element is available in the image.
366              
367             The following key names are common for any image format:
368              
369             =over
370              
371             =item file_media_type
372              
373             This is the MIME type that is appropriate for the given file format.
374             The corresponding value is a string like: "image/png" or "image/jpeg".
375              
376             =item file_ext
377              
378             The is the suggested file name extension for a file of the given file
379             format. The value is a 3 letter, lowercase string like "png", "jpg".
380              
381             =item width
382              
383             This is the number of pixels horizontally in the image.
384              
385             =item height
386              
387             This is the number of pixels vertically in the image. (TIFF uses the
388             name ImageLength for this field.)
389              
390             =item color_type
391              
392             The value is a short string describing what kind of values the pixels
393             encode. The value can be one of the following:
394              
395             Gray
396             GrayA
397             RGB
398             RGBA
399             CMYK
400             YCbCr
401             CIELab
402              
403             These names can also be prefixed by "Indexed-" if the image is
404             composed of indexes into a palette. Of these, only "Indexed-RGB" is
405             likely to occur.
406              
407             It is similar to the TIFF field "PhotometricInterpretation", but this
408             name was found to be too long, so we used the PNG inspired term
409             instead.
410              
411             =item resolution
412              
413             The value of this field normally gives the physical size of the image
414             on screen or paper. When the unit specifier is missing then this field
415             denotes the squareness of pixels in the image.
416              
417             The syntax of this field is:
418              
419             <res> <unit>
420             <xres> "/" <yres> <unit>
421             <xres> "/" <yres>
422              
423             The <res>, <xres> and <yres> fields are numbers. The <unit> is a
424             string like C<dpi>, C<dpm> or C<dpcm> (denoting "dots per
425             inch/cm/meter).
426              
427             =item SamplesPerPixel
428              
429             This says how many channels there are in the image. For some image
430             formats this number might be higher than the number implied from the
431             C<color_type>.
432              
433             =item BitsPerSample
434              
435             This says how many bits are used to encode each of samples. The value
436             is a reference to an array containing numbers. The number of elements
437             in the array should be the same as C<SamplesPerPixel>.
438              
439             =item Comment
440              
441             Textual comments found in the file. The value is a reference to an
442             array if there are multiple comments found.
443              
444             =item Interlace
445              
446             If the image is interlaced, then this tells which interlace method is
447             used.
448              
449             =item Compression
450              
451             This tells you which compression algorithm is used.
452              
453             =item Gamma
454              
455             A number.
456              
457             =item LastModificationTime
458              
459             A ISO date string
460              
461             =back
462              
463             =head1 Supported Image Formats
464              
465             The following image file formats are supported:
466              
467             =over
468              
469              
470             =item AVIF
471              
472             Supports the basic standard info key names.
473              
474             =item BMP
475              
476             This module supports the Microsoft Device Independent Bitmap format
477             (BMP, DIB, RLE).
478              
479             For more information see L<Image::Info::BMP>.
480              
481             =item GIF
482              
483             Both GIF87a and GIF89a are supported and the version number is found
484             as C<GIF_Version> for the first image. GIF files can contain multiple
485             images, and information for all images will be returned if
486             image_info() is called in list context. The Netscape-2.0 extension to
487             loop animation sequences is represented by the C<GIF_Loop> key for the
488             first image. The value is either "forever" or a number indicating
489             loop count.
490              
491             =item ICO
492              
493             This module supports the Microsoft Windows Icon Resource format
494             (.ico).
495              
496             =item JPEG
497              
498             For JPEG files we extract information both from C<JFIF> and C<Exif>
499             application chunks.
500              
501             C<Exif> is the file format written by most digital cameras. This
502             encode things like timestamp, camera model, focal length, exposure
503             time, aperture, flash usage, GPS position, etc.
504              
505             The C<Exif> spec can be found at:
506             L<http://www.exif.org/specifications.html>.
507              
508             The C<color_type> element may have the following values: C<Gray>,
509             C<YCbCr>, and C<CMYK>. Note that detecting C<RGB> and C<YCCK>
510             currently does not work, but will hopefully in future.
511              
512             =item PNG
513              
514             Information from IHDR, PLTE, gAMA, pHYs, tEXt, tIME chunks are
515             extracted. The sequence of chunks are also given by the C<PNG_Chunks>
516             key.
517              
518             =item PBM/PGM/PPM
519              
520             All information available is extracted.
521              
522             =item SVG
523              
524             Provides a plethora of attributes and metadata of an SVG vector graphic.
525              
526             =item TIFF
527              
528             The C<TIFF> spec can be found at:
529             L<http://partners.adobe.com/public/developer/tiff/>
530              
531             The EXIF spec can be found at:
532             L<http://www.exif.org/specifications.html>
533              
534             =item WBMP
535              
536             wbmp files have no magic, so cannot be used with the normal
537             Image::Info functions. See L<Image::Info::WBMP> for more information.
538              
539             =item WEBP
540              
541             VP8 (lossy), VP8L (lossless) and VP8X (extended) files are supported.
542             Sets the key C<Animation> to true if the file is an animation. Otherwise
543             sets the key C<Compression> to either C<VP8> or C<Lossless>.
544              
545             =item XBM
546              
547             See L<Image::Info::XBM> for details.
548              
549             =item XPM
550              
551             See L<Image::Info::XPM> for details.
552              
553             =back
554              
555             =head1 CAVEATS
556              
557             While this module is fine for parsing basic image information like
558             image type, dimensions and color depth, it is probably not good enough
559             for parsing out more advanced information like EXIF data. If you want
560             an up-to-date and tested EXIF parsing library, please use
561             L<Image::ExifTool>.
562              
563             =head1 SEE ALSO
564              
565             L<Image::Size>, L<Image::ExifTool>
566              
567             =head1 AUTHORS
568              
569             Copyright 1999-2004 Gisle Aas.
570              
571             See the CREDITS file for a list of contributors and authors.
572              
573             Tels - (c) 2006 - 2008.
574              
575             Current maintainer: Slaven Rezic - (c) 2008 - 2015.
576              
577             =head1 LICENSE
578              
579             This library is free software; you can redistribute it and/or
580             modify it under the same terms as Perl v5.8.8 itself.
581              
582             =cut
583              
584             # Local Variables:
585             # mode: cperl
586             # End: