parse_image_size.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Parse image size
  2. //
  3. 'use strict';
  4. function parseNextNumber(str, pos, max) {
  5. var code,
  6. start = pos,
  7. result = {
  8. ok: false,
  9. pos: pos,
  10. value: ''
  11. };
  12. code = str.charCodeAt(pos);
  13. while (pos < max && (code >= 0x30 /* 0 */ && code <= 0x39 /* 9 */) || code === 0x25 /* % */) {
  14. code = str.charCodeAt(++pos);
  15. }
  16. result.ok = true;
  17. result.pos = pos;
  18. result.value = str.slice(start, pos);
  19. return result;
  20. }
  21. module.exports = function parseImageSize(str, pos, max) {
  22. var code,
  23. result = {
  24. ok: false,
  25. pos: 0,
  26. width: '',
  27. height: ''
  28. };
  29. if (pos >= max) { return result; }
  30. code = str.charCodeAt(pos);
  31. if (code !== 0x3d /* = */) { return result; }
  32. pos++;
  33. // size must follow = without any white spaces as follows
  34. // (1) =300x200
  35. // (2) =300x
  36. // (3) =x200
  37. code = str.charCodeAt(pos);
  38. if (code !== 0x78 /* x */ && (code < 0x30 || code > 0x39) /* [0-9] */) {
  39. return result;
  40. }
  41. // parse width
  42. var resultW = parseNextNumber(str, pos, max);
  43. pos = resultW.pos;
  44. // next charactor must be 'x'
  45. code = str.charCodeAt(pos);
  46. if (code !== 0x78 /* x */) { return result; }
  47. pos++;
  48. // parse height
  49. var resultH = parseNextNumber(str, pos, max);
  50. pos = resultH.pos;
  51. result.width = resultW.value;
  52. result.height = resultH.value;
  53. result.pos = pos;
  54. result.ok = true;
  55. return result;
  56. };