1Image::Size(3) User Contributed Perl Documentation Image::Size(3)
2
3
4
6 Image::Size - read the dimensions of an image in several popular
7 formats
8
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
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
39 Image::Size provides three interfaces for possible import:
40
41 imgsize(stream)
42 Returns a three-item list of the X and Y dimensions (width and
43 height, in that order) and image type of stream. Errors are noted
44 by undefined (undef) values for the first two elements, and an
45 error string in the third. The third element can be (and usually
46 is) ignored, but is useful when sizing data whose type is unknown.
47
48 html_imgsize(stream)
49 Returns the width and height (X and Y) of stream pre-formatted as a
50 single string 'width="X" height="Y"' suitable for addition into
51 generated HTML IMG tags. If the underlying call to "imgsize" fails,
52 undef is returned. The format returned is dually suited to both
53 HTML and XHTML.
54
55 attr_imgsize(stream)
56 Returns the width and height of stream as part of a 4-element list
57 useful for routines that use hash tables for the manipulation of
58 named parameters, such as the Tk or CGI libraries. A typical return
59 value looks like "("-width", X, "-height", Y)". If the underlying
60 call to "imgsize" fails, undef is returned.
61
62 By default, only "imgsize()" is exported. Any one or combination of the
63 three may be explicitly imported, or all three may be with the tag
64 :all.
65
66 Input Types
67 The sort of data passed as stream can be one of three forms:
68
69 string
70 If an ordinary scalar (string) is passed, it is assumed to be a
71 file name (either absolute or relative to the current working
72 directory of the process) and is searched for and opened (if found)
73 as the source of data. Possible error messages (see DIAGNOSTICS
74 below) may include file-access problems.
75
76 scalar reference
77 If the passed-in stream is a scalar reference, it is interpreted as
78 pointing to an in-memory buffer containing the image data.
79
80 # Assume that &read_data gets data somewhere (WWW, etc.)
81 $img = &read_data;
82 ($x, $y, $id) = imgsize(\$img);
83 # $x and $y are dimensions, $id is the type of the image
84
85 Open file handle
86 The third option is to pass in an open filehandle (such as an
87 object of the "IO::File" class, for example) that has already been
88 associated with the target image file. The file pointer will
89 necessarily move, but will be restored to its original position
90 before subroutine end.
91
92 # $fh was passed in, is IO::File reference:
93 ($x, $y, $id) = imgsize($fh);
94 # Same as calling with filename, but more abstract.
95
96 Recognized Formats
97 Image::Size natively understands and sizes data in the following
98 formats:
99
100 GIF
101 JPG
102 XBM
103 XPM
104 PPM family (PPM/PGM/PBM)
105 XV thumbnails
106 PNG
107 MNG
108 TIF
109 BMP
110 PSD (Adobe PhotoShop)
111 SWF (ShockWave/Flash)
112 CWS (FlashMX, compressed SWF, Flash 6)
113 PCD (Kodak PhotoCD, see notes below)
114
115 Additionally, if the Image::Magick module is present, the file types
116 supported by it are also supported by Image::Size. See also "CAVEATS".
117
118 When using the "imgsize" interface, there is a third, unused value
119 returned if the programmer wishes to save and examine it. This value is
120 the identity of the data type, expressed as a 2-3 letter abbreviation
121 as listed above. This is useful when operating on open file handles or
122 in-memory data, where the type is as unknown as the size. The two
123 support routines ignore this third return value, so those wishing to
124 use it must use the base "imgsize" routine.
125
126 Note that when the Image::Magick fallback is used (for all non-natively
127 supported files), the data type identity comes directly from the
128 'format' parameter reported by Image::Magick, so it may not meet the
129 2-3 letter abbreviation format. For example, a WBMP file might be
130 reported as 'Wireless Bitmap (level 0) image' in this case.
131
132 Information Cacheing and $NO_CACHE
133 When a filename is passed to any of the sizing routines, the default
134 behavior of the library is to cache the resulting information. The
135 modification-time of the file is also recorded, to determine whether
136 the cache should be purged and updated. This was originally added due
137 to the fact that a number of CGI applications were using this library
138 to generate attributes for pages that often used the same graphical
139 element many times over.
140
141 However, the cacheing can lead to problems when the files are generated
142 dynamically, at a rate that exceeds the resolution of the modification-
143 time value on the filesystem. Thus, the optionally-importable control
144 variable $NO_CACHE has been introduced. If this value is anything that
145 evaluates to a non-false value (be that the value 1, any non-null
146 string, etc.) then the cacheing is disabled until such time as the
147 program re-enables it by setting the value to false.
148
149 The parameter $NO_CACHE may be imported as with the imgsize routine,
150 and is also imported when using the import tag ":all". If the
151 programmer chooses not to import it, it is still accessible by the
152 fully-qualified package name, $Image::Size::NO_CACHE.
153
154 Sharing the Cache Between Processes
155 If you are using Image::Size in a multi-thread or multi-process
156 environment, you may wish to enable sharing of the cached information
157 between the processes (or threads). Image::Size does not natively
158 provide any facility for this, as it would add to the list of
159 dependencies.
160
161 To make it possible for users to do this themselves, the %CACHE hash-
162 table that Image::Size uses internally for storage may be imported in
163 the use statement. The user may then make use of packages such as
164 IPC::MMA (IPC::MMA) that can "tie" a hash to a shared-memory segment:
165
166 use Image::Size qw(imgsize %CACHE);
167 use IPC::MMA;
168
169 ...
170
171 tie %CACHE, 'IPC::MM::Hash', $mmHash; # $mmHash via mm_make_hash
172 # Now, forked processes will share any changes made to the cache
173
174 Sizing PhotoCD Images
175 With version 2.95, support for the Kodak PhotoCD image format is
176 included. However, these image files are not quite like the others. One
177 file is the source of the image in any of a range of pre-set
178 resolutions (all with the same aspect ratio). Supporting this here is
179 tricky, since there is nothing inherent in the file to limit it to a
180 specific resolution.
181
182 The library addresses this by using a scale mapping, and requiring the
183 user (you) to specify which scale is preferred for return. Like the
184 $NO_CACHE setting described earlier, this is an importable scalar
185 variable that may be used within the application that uses Image::Size.
186 This parameter is called $PCD_SCALE, and is imported by the same name.
187 It, too, is also imported when using the tag ":all" or may be
188 referenced as $Image::Size::PCD_SCALE.
189
190 The parameter should be set to one of the following values:
191
192 base/16
193 base/4
194 base
195 base4
196 base16
197 base64
198
199 Note that not all PhotoCD disks will have included the "base64"
200 resolution. The actual resolutions are not listed here, as they are
201 constant and can be found in any documentation on the PCD format. The
202 value of $PCD_SCALE is treated in a case-insensitive manner, so "base"
203 is the same as "Base" or "BaSe". The default scale is set to "base".
204
205 Also note that the library makes no effort to read enough of the PCD
206 file to verify that the requested resolution is available. The point of
207 this library is to read as little as necessary so as to operate
208 efficiently. Thus, the only real difference to be found is in whether
209 the orientation of the image is portrait or landscape. That is in fact
210 all that the library extracts from the image file.
211
212 Controlling Behavior with GIF Images
213 GIF images present a sort of unusual situation when it comes to reading
214 size. Because GIFs can be a series of sub-images to be isplayed as an
215 animated sequence, what part does the user want to get the size for?
216
217 When dealing with GIF files, the user may control the behavior by
218 setting the global value $Image::Size::GIF_BEHAVIOR. Like the PCD
219 setting, this may be imported when loading the library. Three values
220 are recognized by the GIF-handling code:
221
222 0 This is the default value. When this value is chosen, the returned
223 dimensions are those of the "screen". The "screen" is the display
224 area that the GIF declares in the first data block of the file. No
225 sub-images will be greater than this in size; if they are, the
226 specification dictates that they be cropped to fit within the box.
227
228 This is also the fastest method for sizing the GIF, as it reads the
229 least amount of data from the image stream.
230
231 1 If this value is set, then the size of the first sub-image within
232 the GIF is returned. For plain (non-animated) GIF files, this would
233 be the same as the screen (though it doesn't have to be, strictly-
234 speaking).
235
236 When the first image descriptor block is read, the code immediately
237 returns, making this only slightly-less efficient than the previous
238 setting.
239
240 2 If this value is chosen, then the code loops through all the sub-
241 images of the animated GIF, and returns the dimensions of the
242 largest of them.
243
244 This option requires that the full GIF image be read, in order to
245 ensure that the largest is found.
246
247 Any value outside this range will produce an error in the GIF code
248 before any image data is read.
249
250 The value of dimensions other than the view-port ("screen") is dubious.
251 However, some users have asked for that functionality.
252
254 There are a few approaches to getting the most out of Image::Size in a
255 multi-process webserver environment. The two most common are pre-
256 caching and using shared memory. These examples are focused on Apache,
257 but should be adaptable to other server approaches as well.
258
259 Pre-Caching Image Data
260 One approach is to include code in an Apache start-up script that reads
261 the information on all images ahead of time. A script loaded via
262 "PerlRequire", for example, becomes part of the server memory before
263 child processes are created. When the children are created, they come
264 into existence with a pre-primed cache already available.
265
266 The shortcoming of this approach is that you have to plan ahead of time
267 for which image files you need to cache. Also, if the list is long-
268 enough it can slow server start-up time.
269
270 The advantage is that it keeps the information centralized in one place
271 and thus easier to manage and maintain. It also requires no additional
272 CPAN modules.
273
274 Shared Memory Caching
275 Another approach is to introduce a shared memory segment that the
276 individual processes all have access to. This can be done with any of a
277 variety of shared memory modules on CPAN.
278
279 Probably the easiest way to do this is to use one of the packages that
280 allow the tying of a hash to a shared memory segment. You can use this
281 in combination with importing the hash table variable that is used by
282 Image::Size for the cache, or you can refer to it explicitly by full
283 package name:
284
285 use IPC::Shareable;
286 use Image::Size;
287
288 tie %Image::Size::CACHE, 'IPC::Shareable', 'size', { create => 1 };
289
290 That example uses IPC::Shareable (see IPC::Shareable) and uses the
291 option to the "tie" command that tells IPC::Shareable to create the
292 segment. Once the initial server process starts to create children,
293 they will all share the tied handle to the memory segment.
294
295 Another package that provides this capability is IPC::MMA (see
296 IPC::MMA), which provides shared memory management via the mm library
297 from Ralf Engelschall (details available in the documentation for
298 IPC::MMA):
299
300 use IPC::MMA;
301 use Image::Size qw(%CACHE);
302
303 my $mm = mm_create(65536, '/tmp/test_lockfile');
304 my $mmHash = mm_make_hash($mm);
305 tie %CACHE, 'IPC::MM::Hash', $mmHash;
306
307 As before, this is done in the start-up phase of the webserver. As the
308 child processes are created, they inherit the pointer to the existing
309 shared segment.
310
312 The attr_imgsize interface is also well-suited to use with the Tk
313 extension:
314
315 $image = $widget->Photo(-file => $img_path, attr_imgsize($img_path));
316
317 Since the "Tk::Image" classes use dashed option names as "CGI" does, no
318 further translation is needed.
319
320 This package is also well-suited for use within an Apache web server
321 context. File sizes are cached upon read (with a check against the
322 modified time of the file, in case of changes), a useful feature for a
323 mod_perl environment in which a child process endures beyond the
324 lifetime of a single request. Other aspects of the mod_perl
325 environment cooperate nicely with this module, such as the ability to
326 use a sub-request to fetch the full pathname for a file within the
327 server space. This complements the HTML generation capabilities of the
328 CGI module, in which "CGI::img" wants a URL but "attr_imgsize" needs a
329 file path:
330
331 # Assume $Q is an object of class CGI, $r is an Apache request object.
332 # $imgpath is a URL for something like "/img/redball.gif".
333 $r->print($Q->img({ -src => $imgpath,
334 attr_imgsize($r->lookup_uri($imgpath)->filename) }));
335
336 The advantage here, besides not having to hard-code the server document
337 root, is that Apache passes the sub-request through the usual request
338 lifecycle, including any stages that would re-write the URL or
339 otherwise modify it.
340
342 The base routine, "imgsize", returns undef as the first value in its
343 list when an error has occured. The third element contains a
344 descriptive error message.
345
346 The other two routines simply return undef in the case of error.
347
349 Caching of size data can only be done on inputs that are file names.
350 Open file handles and scalar references cannot be reliably transformed
351 into a unique key for the table of cache data. Buffers could be cached
352 using the MD5 module, and perhaps in the future I will make that an
353 option. I do not, however, wish to lengthen the dependancy list by
354 another item at this time.
355
356 As Image::Magick operates on file names, not handles, the use of it is
357 restricted to cases where the input to "imgsize" is provided as file
358 name.
359
361 Image::Magick and Image::Info Perl modules at CPAN. The
362 Graphics::Magick Perl API at <http://www.graphicsmagick.org/perl.html>.
363
365 Perl module interface by Randy J. Ray (rjray@blackperl.com), original
366 image-sizing code by Alex Knowles (alex@ed.ac.uk) and Andrew Tong
367 (werdna@ugcs.caltech.edu), used with their joint permission.
368
369 Some bug fixes submitted by Bernd Leibing
370 (bernd.leibing@rz.uni-ulm.de). PPM/PGM/PBM sizing code contributed by
371 Carsten Dominik (dominik@strw.LeidenUniv.nl). Tom Metro (tmetro@vl.com)
372 re-wrote the JPG and PNG code, and also provided a PNG image for the
373 test suite. Dan Klein (dvk@lonewolf.com) contributed a re-write of the
374 GIF code. Cloyce Spradling (cloyce@headgear.org) contributed TIFF
375 sizing code and test images. Aldo Calpini (a.calpini@romagiubileo.it)
376 suggested support of BMP images (which I really should have already
377 thought of :-) and provided code to work with. A patch to allow
378 html_imgsize to produce valid output for XHTML, as well as some
379 documentation fixes was provided by Charles Levert
380 (charles@comm.polymtl.ca). The ShockWave/Flash support was provided by
381 Dmitry Dorofeev (dima@yasp.com). Though I neglected to take note of who
382 supplied the PSD (PhotoShop) code, a bug was identified by Alex
383 Weslowski <aweslowski@rpinteractive.com>, who also provided a test
384 image. PCD support was adapted from a script made available by Phil
385 Greenspun, as guided to my attention by Matt Mueller
386 mueller@wetafx.co.nz. A thorough read of the documentation and source
387 by Philip Newton Philip.Newton@datenrevision.de found several typos and
388 a small buglet. Ville SkyttA~X (ville.skytta@iki.fi) provided the MNG
389 and the Image::Magick fallback code.
390
392 Please report any bugs or feature requests to "bug-image-size at
393 rt.cpan.org", or through the web interface at
394 http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Image-Size
395 <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Image-Size>. I will be
396 notified, and then you'll automatically be notified of progress on your
397 bug as I make changes.
398
400 · RT: CPAN's request tracker
401
402 http://rt.cpan.org/NoAuth/Bugs.html?Dist=Image-Size
403 <http://rt.cpan.org/NoAuth/Bugs.html?Dist=Image-Size>
404
405 · AnnoCPAN: Annotated CPAN documentation
406
407 http://annocpan.org/dist/Image-Size
408 <http://annocpan.org/dist/Image-Size>
409
410 · CPAN Ratings
411
412 http://cpanratings.perl.org/d/Image-Size
413 <http://cpanratings.perl.org/d/Image-Size>
414
415 · Search CPAN
416
417 http://search.cpan.org/dist/Image-Size
418 <http://search.cpan.org/dist/Image-Size>
419
421 This file and the code within are copyright (c) 1996-2009 by Randy J.
422 Ray.
423
424 Copying and distribution are permitted under the terms of the Artistic
425 License 2.0
426 (http://www.opensource.org/licenses/artistic-license-2.0.php
427 <http://www.opensource.org/licenses/artistic-license-2.0.php>) or the
428 GNU LGPL 2.1 (http://www.opensource.org/licenses/lgpl-2.1.php
429 <http://www.opensource.org/licenses/lgpl-2.1.php>).
430
431
432
433perl v5.12.0 2010-05-02 Image::Size(3)