Image-Info-1.22.tar.gz
[Image-Info.git] / dev / Info.pm.tmpl
blob4897dced701be55ace1abd76ed5703a84074f07d
2 #############################################################################
4 # ATTENTION! This file is autogenerated from dev/Info.pm.tmpl - DO NOT EDIT!
6 #############################################################################
8 package Image::Info;
10 # Copyright 1999-2004, Gisle Aas.
12 # This library is free software; you can redistribute it and/or
13 # modify it under the same terms as Perl itself.
15 # Now maintained by Tels - (c) 2006.
17 use strict;
18 use vars qw($VERSION @EXPORT_OK);
20 $VERSION = '1.22';
22 require Exporter;
23 *import = \&Exporter::import;
25 @EXPORT_OK = qw(image_info dim html_dim image_type determine_file_format);
27 # already required and failed sub-modules are remembered here
28 my %mod_failure;
30 sub image_info
32     my $source = _source(shift);
33     return $source if ref $source eq 'HASH'; # Pass on errors
35     # What sort of file is it?
36     my $head = _head($source);
38     return $head if ref($head) eq 'HASH';       # error?
40     my $format = determine_file_format($head)
41         or return { error => 'Unrecognized file format' };
43     no strict 'refs';
44     my $mod = "Image::Info::$format";
45     my $sub = "$mod\::process_file";
46     my $info = bless [], "Image::Info::Result";
47     eval {
48         unless (defined &$sub) {
49             # already required and failed?
50             if (my $fail = $mod_failure{$mod}) {
51                 die $fail;
52             }
53             eval "require $mod";
54             if ($@) {
55                 $mod_failure{$mod} = $@;
56                 die $@;
57             }
58             die "$mod did not define &$sub" unless defined &$sub;
59         }
61         my %cnf = @_;
62         # call process_file()
63         &$sub($info, $source, \%cnf);
64         $info->clean_up;
65     };
66     return { error => $@ } if $@;
67     return wantarray ? @$info : $info->[0];
70 sub image_type
72     my $source = _source(shift);
73     return $source if ref $source eq 'HASH'; # Pass on errors
75     # What sort of file is it?
76     my $head = _head($source) or return _os_err("Can't read head");
77     my $format = determine_file_format($head)
78         or return { error => "Unrecognized file format" };
80     return { file_type => $format };
83 sub _source
85     my $source = shift;
86     if (!ref $source) {
87         require Symbol;
88         my $fh = Symbol::gensym();
89         open($fh, $source) || return _os_err("Can't open $source");
90         ${*$fh} = $source;  # keep filename in case somebody wants to know
91         binmode($fh);
92         $source = $fh;
93     }
94     elsif (ref($source) eq "SCALAR") {
95         if ($] >= 5.008) {
96             open(my $s, "<", $source) or return _os_err("Can't open string");
97             $source = $s;
98         }
99         else {
100             require IO::String;
101             $source = IO::String->new($$source);
102         }
103     }
104     else {
105         seek($source, 0, 0) or return _os_err("Can't rewind");
106     }
108     $source;
111 sub _head
113     my $source = shift;
114     my $head;
116     # tiny.pgm is 11 bytes
117     my $to_read = 11;
118     my $read = read($source, $head, $to_read);
120     return _os_err("Couldn't read $to_read bytes") if $read != $to_read;
122     if (ref($source) eq "IO::String") {
123         # XXX workaround until we can trap seek() with a tied file handle
124         $source->setpos(0);
125     }
126     else {
127         seek($source, 0, 0) or return _os_err("Can't rewind");
128     }
129     $head;
132 sub _os_err
134     return { error => "$_[0]: $!",
135              Errno => $!+0,
136            };
139 %%DETERMINE_FILE_FORMAT%%
141 sub dim
143     my $img = shift || return;
144     my $x = $img->{width} || return;
145     my $y = $img->{height} || return;
146     wantarray ? ($x, $y) : "${x}x$y";
149 sub html_dim
151     my($x, $y) = dim(@_);
152     return "" unless $x;
153     "width=\"$x\" height=\"$y\"";
156 #############################################################################
157 package Image::Info::Result;
159 sub push_info
161     my($self, $n, $key) = splice(@_, 0, 3);
162     push(@{$self->[$n]{$key}}, @_);
165 sub clean_up
167     my $self = shift;
168     for (@$self) {
169         for my $k (keys %$_) {
170             my $a = $_->{$k};
171             $_->{$k} = $a->[0] if @$a <= 1;
172         }
173     }
176 sub get_info {
177     my($self, $n, $key, $delete) = @_;
178     my $v = $delete ? delete $self->[$n]{$key} : $self->[$n]{$key};
179     $v ||= [];
180     @$v;
185 __END__
187 =head1 NAME
189 Image::Info - Extract meta information from image files
191 =head1 SYNOPSIS
193  use Image::Info qw(image_info dim);
195  my $info = image_info("image.jpg");
196  if (my $error = $info->{error}) {
197      die "Can't parse image info: $error\n";
199  my $color = $info->{color_type};
201  my $type = image_type("image.jpg");
202  if (my $error = $type->{error}) {
203      die "Can't determine file type: $error\n";
205  die "No gif files allowed!" if $type->{file_type} eq 'GIF';
207  my($w, $h) = dim($info);
209 =head1 DESCRIPTION
211 This module provide functions to extract various kind of meta
212 information from image files.
214 =head2 EXPORTS
216 Exports nothing by default, but can export the following methods
217 on request:
219         image_info
220         image_type
221         dim
222         html_dim
223         determine_file_type
225 =head2 METHODS
227 The following functions are provided by the C<Image::Info> module:
229 =over
231 =item image_info( $file )
233 =item image_info( \$imgdata )
235 =item image_info( $file, key => value,... )
237 This function takes the name of a file or a file handle as argument
238 and will return one or more hashes (actually hash references)
239 describing the images inside the file.  If there is only one image in
240 the file only one hash is returned.  In scalar context, only the hash
241 for the first image is returned.
243 In case of error, and hash containing the "error" key will be
244 returned.  The corresponding value will be an appropriate error
245 message.
247 If a reference to a scalar is passed as argument to this function,
248 then it is assumed that this scalar contains the raw image data
249 directly.
251 The image_info() function also take optional key/value style arguments
252 that can influence what information is returned.
254 =item image_type( $filename )
256 Returns a hash with only one key, C<< file_type >>. The value
257 will be the type of the file. On error, sets the two keys
258 C<< error >> and C<< Errno >>.
260 =item image_info( \$imgdata )
262 This function is a dramatically faster alternative to the image_info
263 function for situations in which you B<only> need to find the image type.
265 It uses only the internal file-type detection to do this, and thus does
266 not need to load any of the image type-specific driver modules, and does
267 not access to entire file. It also only needs access to the first 32
268 bytes of the file.
270 To maintain some level of compatibility with image_info, image_type
271 returns in the same format, with the same error message style. That is,
272 it returns a HASH reference, with the $type->{error} key set if there
273 was an error.
275 On success, the HASH reference will contain the single key 'file_type',
276 which represents the type of the file, expressed as the type code used for
277 the various drivers ('GIF', 'JPEG', 'TIFF' and so on).
279 If there are multiple images within the file they will be ignored, as this
280 function provides only the type of the overall file, not of the various
281 images within it. This function will not return multiple hashes if the file
282 contains multiple images.
284 Of course, in all (or at least effectively all) cases the type of the images
285 inside the file is going to be the same as that of the file itself.
287 =item dim( $info_hash )
289 Takes an hash as returned from image_info() and returns the dimensions
290 ($width, $height) of the image.  In scalar context returns the
291 dimensions as a string.
293 =item html_dim( $info_hash )
295 Returns the dimensions as a string suitable for embedding directly
296 into HTML or SVG <img>-tags. E.g.:
298    print "<img src="..." @{[html_dim($info)]}>\n";
300 =item determine_file_format( $filedata )
302 Determines the file format from the passed file data (a normal Perl
303 scalar containing the first bytes of the file), and returns
304 either undef for an unknown file format, or a string describing
305 the format, like "BMP" or "JPEG".
307 =back
309 =head1 Image descriptions
311 The image_info() function returns meta information about each image in
312 the form of a reference to a hash.  The hash keys used are in most
313 cases based on the TIFF element names.  All lower case keys are
314 mandatory for all file formats and will always be there unless an
315 error occured (in which case the "error" key will be present.)  Mixed
316 case keys will only be present when the corresponding information
317 element is available in the image.
319 The following key names are common for any image format:
321 =over
323 =item file_media_type
325 This is the MIME type that is appropriate for the given file format.
326 The corresponding value is a string like: "image/png" or "image/jpeg".
328 =item file_ext
330 The is the suggested file name extention for a file of the given file
331 format.  The value is a 3 letter, lowercase string like "png", "jpg".
333 =item width
335 This is the number of pixels horizontally in the image.
337 =item height
339 This is the number of pixels vertically in the image.  (TIFF use the
340 name ImageLength for this field.)
342 =item color_type
344 The value is a short string describing what kind of values the pixels
345 encode.  The value can be one of the following:
347   Gray
348   GrayA
349   RGB
350   RGBA
351   CMYK
352   YCbCr
353   CIELab
355 These names can also be prefixed by "Indexed-" if the image is
356 composed of indexes into a palette.  Of these, only "Indexed-RGB" is
357 likely to occur.
359 It is similar to the TIFF field PhotometricInterpretation, but this
360 name was found to be too long, so we used the PNG inpired term
361 instead.
363 =item resolution
365 The value of this field normally gives the physical size of the image
366 on screen or paper. When the unit specifier is missing then this field
367 denotes the squareness of pixels in the image.
369 The syntax of this field is:
371    <res> <unit>
372    <xres> "/" <yres> <unit>
373    <xres> "/" <yres>
375 The <res>, <xres> and <yres> fields are numbers.  The <unit> is a
376 string like C<dpi>, C<dpm> or C<dpcm> (denoting "dots per
377 inch/cm/meter).
379 =item SamplesPerPixel
381 This says how many channels there are in the image.  For some image
382 formats this number might be higher than the number implied from the
383 C<color_type>.
385 =item BitsPerSample
387 This says how many bits are used to encode each of samples.  The value
388 is a reference to an array containing numbers. The number of elements
389 in the array should be the same as C<SamplesPerPixel>.
391 =item Comment
393 Textual comments found in the file.  The value is a reference to an
394 array if there are multiple comments found.
396 =item Interlace
398 If the image is interlaced, then this tell which interlace method is
399 used.
401 =item Compression
403 This tells you which compression algorithm is used.
405 =item Gamma
407 A number.
409 =item LastModificationTime
411 A ISO date string
413 =back
415 =head1 Supported Image Formats
417 The following image file formats are supported:
419 =over
421 %%FORMAT_DESC%%
423 =back
425 =head1 CAVEATS
427 Note that while the module is still maintained, no new features
428 will be added.
430 Especially the EXIF parsing code is buggy, not tested at all,
431 and quite incomplete (a lot of manufacturer's MakerNotes and tags are
432 not parsed at all). If you want a stable, feature-complete, up-to-date
433 and tested EXIF parsing library, please use Image::ExifTool. 
435 =head1 SEE ALSO
437 L<Image::Size>, L<Image::ExifTool>
439 =head1 AUTHORS
441 Copyright 1999-2004 Gisle Aas.
443 See the CREDITS file for a list of contributors and authors.
445 Now maintained by Tels - (c) 2006.
447 =head1 LICENSE
449 This library is free software; you can redistribute it and/or
450 modify it under the same terms as Perl itself.
452 =cut