image.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. 'use strict'
  2. /*!
  3. * Canvas - Image
  4. * Copyright (c) 2010 LearnBoost <tj@learnboost.com>
  5. * MIT Licensed
  6. */
  7. /**
  8. * Module dependencies.
  9. */
  10. const bindings = require('./bindings')
  11. const Image = module.exports = bindings.Image
  12. const util = require('util')
  13. // Lazily loaded simple-get
  14. let get
  15. const { GetSource, SetSource } = bindings
  16. Object.defineProperty(Image.prototype, 'src', {
  17. /**
  18. * src setter. Valid values:
  19. * * `data:` URI
  20. * * Local file path
  21. * * HTTP or HTTPS URL
  22. * * Buffer containing image data (i.e. not a `data:` URI stored in a Buffer)
  23. *
  24. * @param {String|Buffer} val filename, buffer, data URI, URL
  25. * @api public
  26. */
  27. set (val) {
  28. if (typeof val === 'string') {
  29. if (/^\s*data:/.test(val)) { // data: URI
  30. const commaI = val.indexOf(',')
  31. // 'base64' must come before the comma
  32. const isBase64 = val.lastIndexOf('base64', commaI) !== -1
  33. const content = val.slice(commaI + 1)
  34. setSource(this, Buffer.from(content, isBase64 ? 'base64' : 'utf8'), val)
  35. } else if (/^\s*https?:\/\//.test(val)) { // remote URL
  36. const onerror = err => {
  37. if (typeof this.onerror === 'function') {
  38. this.onerror(err)
  39. } else {
  40. throw err
  41. }
  42. }
  43. if (!get) get = require('simple-get')
  44. get.concat({
  45. url: val,
  46. headers: { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36' }
  47. }, (err, res, data) => {
  48. if (err) return onerror(err)
  49. if (res.statusCode < 200 || res.statusCode >= 300) {
  50. return onerror(new Error(`Server responded with ${res.statusCode}`))
  51. }
  52. setSource(this, data)
  53. })
  54. } else { // local file path assumed
  55. setSource(this, val)
  56. }
  57. } else if (Buffer.isBuffer(val)) {
  58. setSource(this, val)
  59. }
  60. },
  61. get () {
  62. // TODO https://github.com/Automattic/node-canvas/issues/118
  63. return getSource(this)
  64. },
  65. configurable: true
  66. })
  67. // TODO || is for Node.js pre-v6.6.0
  68. Image.prototype[util.inspect.custom || 'inspect'] = function () {
  69. return '[Image' +
  70. (this.complete ? ':' + this.width + 'x' + this.height : '') +
  71. (this.src ? ' ' + this.src : '') +
  72. (this.complete ? ' complete' : '') +
  73. ']'
  74. }
  75. function getSource (img) {
  76. return img._originalSource || GetSource.call(img)
  77. }
  78. function setSource (img, src, origSrc) {
  79. SetSource.call(img, src)
  80. img._originalSource = origSrc
  81. }