1Image::Size(3)        User Contributed Perl Documentation       Image::Size(3)
2
3
4

NAME

6       Image::Size - read the dimensions of an image in several popular
7       formats
8

SYNOPSIS

10           use Image::Size;
11           # Get the size of globe.gif
12           ($globe_x, $globe_y) = imgsize("globe.gif");
13           # Assume X=60 and Y=40 for remaining examples
14
15           use Image::Size 'html_imgsize';
16           # Get the size as 'width="X" height="Y"' for HTML generation
17           $size = html_imgsize("globe.gif");
18           # $size == 'width="60" height="40"'
19
20           use Image::Size 'attr_imgsize';
21           # Get the size as a list passable to routines in CGI.pm
22           @attrs = attr_imgsize("globe.gif");
23           # @attrs == ('-width', 60, '-height', 40)
24
25           use Image::Size;
26           # Get the size of an in-memory buffer
27           ($buf_x, $buf_y) = imgsize(\$buf);
28           # Assuming that $buf was the data, imgsize() needed a
29           $ reference to a scalar
30

DESCRIPTION

32       The Image::Size library is based upon the "wwwis" script written by
33       Alex Knowles (alex@ed.ac.uk), a tool to examine HTML and add 'width'
34       and 'height' parameters to image tags. The sizes are cached internally
35       based on file name, so multiple calls on the same file name (such as
36       images used in bulleted lists, for example) do not result in repeated
37       computations.
38

SUBROUTINES/METHODS

40       Image::Size provides three interfaces for possible import:
41
42       imgsize(stream)
43           Returns a three-item list of the X and Y dimensions (width and
44           height, in that order) and image type of stream. Errors are noted
45           by undefined (undef) values for the first two elements, and an
46           error string in the third.  The third element can be (and usually
47           is) ignored, but is useful when sizing data whose type is unknown.
48
49       html_imgsize(stream)
50           Returns the width and height (X and Y) of stream pre-formatted as a
51           single string 'width="X" height="Y"' suitable for addition into
52           generated HTML IMG tags. If the underlying call to "imgsize" fails,
53           undef is returned. The format returned is dually suited to both
54           HTML and XHTML.
55
56       attr_imgsize(stream)
57           Returns the width and height of stream as part of a 4-element list
58           useful for routines that use hash tables for the manipulation of
59           named parameters, such as the Tk or CGI libraries. A typical return
60           value looks like "("-width", X, "-height", Y)". If the underlying
61           call to "imgsize" fails, undef is returned.
62
63       By default, only "imgsize()" is exported. Any one or combination of the
64       three may be explicitly imported, or all three may be with the tag
65       :all.
66
67   Input Types
68       The sort of data passed as stream can be one of three forms:
69
70       string
71           If an ordinary scalar (string) is passed, it is assumed to be a
72           file name (either absolute or relative to the current working
73           directory of the process) and is searched for and opened (if found)
74           as the source of data.  Possible error messages (see DIAGNOSTICS
75           below) may include file-access problems.
76
77       scalar reference
78           If the passed-in stream is a scalar reference, it is interpreted as
79           pointing to an in-memory buffer containing the image data.
80
81                   # Assume that &read_data gets data somewhere (WWW, etc.)
82                   $img = &read_data;
83                   ($x, $y, $id) = imgsize(\$img);
84                   # $x and $y are dimensions, $id is the type of the image
85
86       Open file handle
87           The third option is to pass in an open filehandle (such as an
88           object of the "IO::File" class, for example) that has already been
89           associated with the target image file. The file pointer will
90           necessarily move, but will be restored to its original position
91           before subroutine end.
92
93                   # $fh was passed in, is IO::File reference:
94                   ($x, $y, $id) = imgsize($fh);
95                   # Same as calling with filename, but more abstract.
96
97   Recognized Formats
98       Image::Size natively understands and sizes data in the following
99       formats:
100
101       GIF
102       JPG
103       XBM
104       XPM
105       PPM family (PPM/PGM/PBM)
106       XV thumbnails
107       PNG
108       MNG
109       TIF
110       BMP
111       PSD (Adobe PhotoShop)
112       SWF (ShockWave/Flash)
113       CWS (FlashMX, compressed SWF, Flash 6)
114       PCD (Kodak PhotoCD, see notes below)
115       EMF (Windows Enhanced Metafile Format)
116       WEBP
117       ICO (Microsoft icon format)
118       CUR (Microsoft mouse cursor format)
119
120       Additionally, if the Image::Magick module is present, the file types
121       supported by it are also supported by Image::Size.  See also "CAVEATS".
122
123       When using the "imgsize" interface, there is a third, unused value
124       returned if the programmer wishes to save and examine it. This value is
125       the identity of the data type, expressed as a 2-3 letter abbreviation
126       as listed above. This is useful when operating on open file handles or
127       in-memory data, where the type is as unknown as the size.  The two
128       support routines ignore this third return value, so those wishing to
129       use it must use the base "imgsize" routine.
130
131       Note that when the Image::Magick fallback is used (for all non-natively
132       supported files), the data type identity comes directly from the
133       'format' parameter reported by Image::Magick, so it may not meet the
134       2-3 letter abbreviation format.  For example, a WBMP file might be
135       reported as 'Wireless Bitmap (level 0) image' in this case.
136
137   Information Caching and $NO_CACHE
138       When a filename is passed to any of the sizing routines, the default
139       behavior of the library is to cache the resulting information. The
140       modification-time of the file is also recorded, to determine whether
141       the cache should be purged and updated. This was originally added due
142       to the fact that a number of CGI applications were using this library
143       to generate attributes for pages that often used the same graphical
144       element many times over.
145
146       However, the caching can lead to problems when the files are generated
147       dynamically, at a rate that exceeds the resolution of the modification-
148       time value on the filesystem. Thus, the optionally-importable control
149       variable $NO_CACHE has been introduced. If this value is anything that
150       evaluates to a non-false value (be that the value 1, any non-null
151       string, etc.) then the cacheing is disabled until such time as the
152       program re-enables it by setting the value to false.
153
154       The parameter $NO_CACHE may be imported as with the imgsize routine,
155       and is also imported when using the import tag ":all". If the
156       programmer chooses not to import it, it is still accessible by the
157       fully-qualified package name, $Image::Size::NO_CACHE.
158
159   Sharing the Cache Between Processes
160       If you are using Image::Size in a multi-thread or multi-process
161       environment, you may wish to enable sharing of the cached information
162       between the processes (or threads). Image::Size does not natively
163       provide any facility for this, as it would add to the list of
164       dependencies.
165
166       To make it possible for users to do this themselves, the %CACHE hash-
167       table that Image::Size uses internally for storage may be imported in
168       the use statement. The user may then make use of packages such as
169       IPC::MMA (IPC::MMA) that can "tie" a hash to a shared-memory segment:
170
171           use Image::Size qw(imgsize %CACHE);
172           use IPC::MMA;
173
174           ...
175
176           tie %CACHE, 'IPC::MM::Hash', $mmHash; # $mmHash via mm_make_hash
177           # Now, forked processes will share any changes made to the cache
178
179   Sizing PhotoCD Images
180       With version 2.95, support for the Kodak PhotoCD image format is
181       included. However, these image files are not quite like the others. One
182       file is the source of the image in any of a range of pre-set
183       resolutions (all with the same aspect ratio). Supporting this here is
184       tricky, since there is nothing inherent in the file to limit it to a
185       specific resolution.
186
187       The library addresses this by using a scale mapping, and requiring the
188       user (you) to specify which scale is preferred for return. Like the
189       $NO_CACHE setting described earlier, this is an importable scalar
190       variable that may be used within the application that uses Image::Size.
191       This parameter is called $PCD_SCALE, and is imported by the same name.
192       It, too, is also imported when using the tag ":all" or may be
193       referenced as $Image::Size::PCD_SCALE.
194
195       The parameter should be set to one of the following values:
196
197               base/16
198               base/4
199               base
200               base4
201               base16
202               base64
203
204       Note that not all PhotoCD disks will have included the "base64"
205       resolution. The actual resolutions are not listed here, as they are
206       constant and can be found in any documentation on the PCD format. The
207       value of $PCD_SCALE is treated in a case-insensitive manner, so "base"
208       is the same as "Base" or "BaSe". The default scale is set to "base".
209
210       Also note that the library makes no effort to read enough of the PCD
211       file to verify that the requested resolution is available. The point of
212       this library is to read as little as necessary so as to operate
213       efficiently. Thus, the only real difference to be found is in whether
214       the orientation of the image is portrait or landscape. That is in fact
215       all that the library extracts from the image file.
216
217   Controlling Behavior with GIF Images
218       GIF images present a sort of unusual situation when it comes to reading
219       size.  Because GIFs can be a series of sub-images to be played as an
220       animated sequence, what part does the user want to get the size for?
221
222       When dealing with GIF files, the user may control the behavior by
223       setting the global value $Image::Size::GIF_BEHAVIOR. Like the PCD
224       setting, this may be imported when loading the library. Three values
225       are recognized by the GIF-handling code:
226
227       0   This is the default value. When this value is chosen, the returned
228           dimensions are those of the "screen". The "screen" is the display
229           area that the GIF declares in the first data block of the file. No
230           sub-images will be greater than this in size; if they are, the
231           specification dictates that they be cropped to fit within the box.
232
233           This is also the fastest method for sizing the GIF, as it reads the
234           least amount of data from the image stream.
235
236       1   If this value is set, then the size of the first sub-image within
237           the GIF is returned. For plain (non-animated) GIF files, this would
238           be the same as the screen (though it doesn't have to be, strictly-
239           speaking).
240
241           When the first image descriptor block is read, the code immediately
242           returns, making this only slightly-less efficient than the previous
243           setting.
244
245       2   If this value is chosen, then the code loops through all the sub-
246           images of the animated GIF, and returns the dimensions of the
247           largest of them.
248
249           This option requires that the full GIF image be read, in order to
250           ensure that the largest is found.
251
252       Any value outside this range will produce an error in the GIF code
253       before any image data is read.
254
255       The value of dimensions other than the view-port ("screen") is dubious.
256       However, some users have asked for that functionality.
257

Image::Size AND WEBSERVERS

259       There are a few approaches to getting the most out of Image::Size in a
260       multi-process webserver environment. The two most common are pre-
261       caching and using shared memory. These examples are focused on Apache,
262       but should be adaptable to other server approaches as well.
263
264   Pre-Caching Image Data
265       One approach is to include code in an Apache start-up script that reads
266       the information on all images ahead of time. A script loaded via
267       "PerlRequire", for example, becomes part of the server memory before
268       child processes are created. When the children are created, they come
269       into existence with a pre-primed cache already available.
270
271       The shortcoming of this approach is that you have to plan ahead of time
272       for which image files you need to cache. Also, if the list is long-
273       enough it can slow server start-up time.
274
275       The advantage is that it keeps the information centralized in one place
276       and thus easier to manage and maintain. It also requires no additional
277       CPAN modules.
278
279   Shared Memory Caching
280       Another approach is to introduce a shared memory segment that the
281       individual processes all have access to. This can be done with any of a
282       variety of shared memory modules on CPAN.
283
284       Probably the easiest way to do this is to use one of the packages that
285       allow the tying of a hash to a shared memory segment. You can use this
286       in combination with importing the hash table variable that is used by
287       Image::Size for the cache, or you can refer to it explicitly by full
288       package name:
289
290           use IPC::Shareable;
291           use Image::Size;
292
293           tie %Image::Size::CACHE, 'IPC::Shareable', 'size', { create => 1 };
294
295       That example uses IPC::Shareable (see IPC::Shareable) and uses the
296       option to the "tie" command that tells IPC::Shareable to create the
297       segment. Once the initial server process starts to create children,
298       they will all share the tied handle to the memory segment.
299
300       Another package that provides this capability is IPC::MMA (see
301       IPC::MMA), which provides shared memory management via the mm library
302       from Ralf Engelschall (details available in the documentation for
303       IPC::MMA):
304
305           use IPC::MMA;
306           use Image::Size qw(%CACHE);
307
308           my $mm = mm_create(65536, '/tmp/test_lockfile');
309           my $mmHash = mm_make_hash($mm);
310           tie %CACHE, 'IPC::MM::Hash', $mmHash;
311
312       As before, this is done in the start-up phase of the webserver. As the
313       child processes are created, they inherit the pointer to the existing
314       shared segment.
315

MORE EXAMPLES

317       The attr_imgsize interface is also well-suited to use with the Tk
318       extension:
319
320           $image = $widget->Photo(-file => $img_path, attr_imgsize($img_path));
321
322       Since the "Tk::Image" classes use dashed option names as "CGI" does, no
323       further translation is needed.
324
325       This package is also well-suited for use within an Apache web server
326       context.  File sizes are cached upon read (with a check against the
327       modified time of the file, in case of changes), a useful feature for a
328       mod_perl environment in which a child process endures beyond the
329       lifetime of a single request.  Other aspects of the mod_perl
330       environment cooperate nicely with this module, such as the ability to
331       use a sub-request to fetch the full pathname for a file within the
332       server space. This complements the HTML generation capabilities of the
333       CGI module, in which "CGI::img" wants a URL but "attr_imgsize" needs a
334       file path:
335
336           # Assume $Q is an object of class CGI, $r is an Apache request object.
337           # $imgpath is a URL for something like "/img/redball.gif".
338           $r->print($Q->img({ -src => $imgpath,
339                               attr_imgsize($r->lookup_uri($imgpath)->filename) }));
340
341       The advantage here, besides not having to hard-code the server document
342       root, is that Apache passes the sub-request through the usual request
343       lifecycle, including any stages that would re-write the URL or
344       otherwise modify it.
345

DIAGNOSTICS

347       The base routine, "imgsize", returns undef as the first value in its
348       list when an error has occurred. The third element contains a
349       descriptive error message.
350
351       The other two routines simply return undef in the case of error.
352

CAVEATS

354       Caching of size data can only be done on inputs that are file names.
355       Open file handles and scalar references cannot be reliably transformed
356       into a unique key for the table of cache data. Buffers could be cached
357       using the MD5 module, and perhaps in the future I will make that an
358       option. I do not, however, wish to lengthen the dependency list by
359       another item at this time.
360
361       As Image::Magick operates on file names, not handles, the use of it is
362       restricted to cases where the input to "imgsize" is provided as file
363       name.
364

SEE ALSO

366       Image::Magick and Image::Info Perl modules at CPAN. The
367       Graphics::Magick Perl API at <http://www.graphicsmagick.org/perl.html>.
368

CONTRIBUTORS

370       Perl module interface by Randy J. Ray (rjray@blackperl.com), original
371       image-sizing code by Alex Knowles (alex@ed.ac.uk) and Andrew Tong
372       (werdna@ugcs.caltech.edu), used with their joint permission.
373
374       Some bug fixes submitted by Bernd Leibing
375       (bernd.leibing@rz.uni-ulm.de).  PPM/PGM/PBM sizing code contributed by
376       Carsten Dominik (dominik@strw.LeidenUniv.nl). Tom Metro (tmetro@vl.com)
377       re-wrote the JPG and PNG code, and also provided a PNG image for the
378       test suite. Dan Klein (dvk@lonewolf.com) contributed a re-write of the
379       GIF code.  Cloyce Spradling (cloyce@headgear.org) contributed TIFF
380       sizing code and test images. Aldo Calpini (a.calpini@romagiubileo.it)
381       suggested support of BMP images (which I really should have already
382       thought of :-) and provided code to work with. A patch to allow
383       html_imgsize to produce valid output for XHTML, as well as some
384       documentation fixes was provided by Charles Levert
385       (charles@comm.polymtl.ca). The ShockWave/Flash support was provided by
386       Dmitry Dorofeev (dima@yasp.com). Though I neglected to take note of who
387       supplied the PSD (PhotoShop) code, a bug was identified by Alex
388       Weslowski <aweslowski@rpinteractive.com>, who also provided a test
389       image. PCD support was adapted from a script made available by Phil
390       Greenspun, as guided to my attention by Matt Mueller
391       mueller@wetafx.co.nz. A thorough read of the documentation and source
392       by Philip Newton Philip.Newton@datenrevision.de found several typos and
393       a small buglet. Ville Skytt� (ville.skytta@iki.fi) provided the MNG and
394       the Image::Magick fallback code. Craig MacKenna
395       (mackenna@animalhead.com) suggested making the cache available so that
396       it could be used with shared memory, and helped test my change before
397       release.
398

BUGS

400       Please report any bugs or feature requests to "bug-image-size at
401       rt.cpan.org", or through the web interface at
402       <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Image-Size>. I will be
403       notified, and then you'll automatically be notified of progress on your
404       bug as I make changes.
405

SUPPORT

407       •   RT: CPAN's request tracker
408
409           <http://rt.cpan.org/NoAuth/Bugs.html?Dist=Image-Size>
410
411       •   AnnoCPAN: Annotated CPAN documentation
412
413           <http://annocpan.org/dist/Image-Size>
414
415       •   CPAN Ratings
416
417           <http://cpanratings.perl.org/d/Image-Size>
418
419       •   Search CPAN
420
421           <http://search.cpan.org/dist/Image-Size>
422
423       •   Project page on GitHub
424
425           <http://github.com/rjray/image-size>
426

REPOSITORY

428       <https://github.com/rjray/image-size>
429
431       This file and the code within are copyright (c) 1996-2009 by Randy J.
432       Ray.
433
434       Copying and distribution are permitted under the terms of the Artistic
435       License 2.0
436       (<http://www.opensource.org/licenses/artistic-license-2.0.php>) or the
437       GNU LGPL 2.1 (<http://www.opensource.org/licenses/lgpl-2.1.php>).
438

AUTHOR

440       Randy J. Ray "<rjray@blackperl.com>"
441
442
443
444perl v5.32.1                      2021-01-27                    Image::Size(3)
Impressum