image-size.js 1.2 KB

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