1 | var utils = require('../utils')
|
2 | , nodes = require('../nodes')
|
3 | , Image = require('./image');
|
4 |
|
5 | /**
|
6 | * Return the width and height of the given `img` path.
|
7 | *
|
8 | * Examples:
|
9 | *
|
10 | * image-size('foo.png')
|
11 | * // => 200px 100px
|
12 | *
|
13 | * image-size('foo.png')[0]
|
14 | * // => 200px
|
15 | *
|
16 | * image-size('foo.png')[1]
|
17 | * // => 100px
|
18 | *
|
19 | * Can be used to test if the image exists,
|
20 | * using an optional argument set to `true`
|
21 | * (without this argument this function throws error
|
22 | * if there is no such image).
|
23 | *
|
24 | * Example:
|
25 | *
|
26 | * image-size('nosuchimage.png', true)[0]
|
27 | * // => 0
|
28 | *
|
29 | * @param {String} img
|
30 | * @param {Boolean} ignoreErr
|
31 | * @return {Expression}
|
32 | * @api public
|
33 | */
|
34 |
|
35 | function imageSize(img, ignoreErr) {
|
36 | utils.assertType(img, 'string', 'img');
|
37 | try {
|
38 | var img = new Image(this, img.string);
|
39 | } catch (err) {
|
40 | if (ignoreErr) {
|
41 | return [new nodes.Unit(0), new nodes.Unit(0)];
|
42 | } else {
|
43 | throw err;
|
44 | }
|
45 | }
|
46 |
|
47 | // Read size
|
48 | img.open();
|
49 | var size = img.size();
|
50 | img.close();
|
51 |
|
52 | // Return (w h)
|
53 | var expr = [];
|
54 | expr.push(new nodes.Unit(size[0], 'px'));
|
55 | expr.push(new nodes.Unit(size[1], 'px'));
|
56 |
|
57 | return expr;
|
58 | };
|
59 | imageSize.params = ['img', 'ignoreErr'];
|
60 | module.exports = imageSize;
|