load-image.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. const fs = require('fs')
  2. const { Readable } = require('stream')
  3. const { URL } = require('url')
  4. const { Image } = require('./js-binding')
  5. let http, https
  6. const MAX_REDIRECTS = 20
  7. const REDIRECT_STATUSES = new Set([301, 302])
  8. /**
  9. * Loads the given source into canvas Image
  10. * @param {string|URL|Image|Buffer} source The image source to be loaded
  11. * @param {object} options Options passed to the loader
  12. */
  13. module.exports = async function loadImage(source, options = {}) {
  14. // use the same buffer without copying if the source is a buffer
  15. if (Buffer.isBuffer(source) || source instanceof Uint8Array) return createImage(source, options.alt)
  16. // load readable stream as image
  17. if (source instanceof Readable) return createImage(await consumeStream(source), options.alt)
  18. // construct a Uint8Array if the source is ArrayBuffer or SharedArrayBuffer
  19. if (source instanceof ArrayBuffer || source instanceof SharedArrayBuffer)
  20. return createImage(new Uint8Array(source), options.alt)
  21. // construct a buffer if the source is buffer-like
  22. if (isBufferLike(source)) return createImage(Buffer.from(source), options.alt)
  23. // if the source is Image instance, copy the image src to new image
  24. if (source instanceof Image) return createImage(source.src, options.alt)
  25. // if source is string and in data uri format, construct image using data uri
  26. if (typeof source === 'string' && source.trimStart().startsWith('data:')) {
  27. const commaIdx = source.indexOf(',')
  28. const encoding = source.lastIndexOf('base64', commaIdx) < 0 ? 'utf-8' : 'base64'
  29. const data = Buffer.from(source.slice(commaIdx + 1), encoding)
  30. return createImage(data, options.alt)
  31. }
  32. // if source is a string or URL instance
  33. if (typeof source === 'string') {
  34. // if the source exists as a file, construct image from that file
  35. if (!source.startsWith('http') && !source.startsWith('https') && (await exists(source))) {
  36. return createImage(source, options.alt)
  37. } else {
  38. // the source is a remote url here
  39. source = new URL(source)
  40. // attempt to download the remote source and construct image
  41. const data = await new Promise((resolve, reject) =>
  42. makeRequest(
  43. source,
  44. resolve,
  45. reject,
  46. typeof options.maxRedirects === 'number' && options.maxRedirects >= 0 ? options.maxRedirects : MAX_REDIRECTS,
  47. options.requestOptions,
  48. ),
  49. )
  50. return createImage(data, options.alt)
  51. }
  52. }
  53. if (source instanceof URL) {
  54. if (source.protocol === 'file:') {
  55. // remove the leading slash on windows
  56. return createImage(process.platform === 'win32' ? source.pathname.substring(1) : source.pathname, options.alt)
  57. } else {
  58. const data = await new Promise((resolve, reject) =>
  59. makeRequest(
  60. source,
  61. resolve,
  62. reject,
  63. typeof options.maxRedirects === 'number' && options.maxRedirects >= 0 ? options.maxRedirects : MAX_REDIRECTS,
  64. options.requestOptions,
  65. ),
  66. )
  67. return createImage(data, options.alt)
  68. }
  69. }
  70. // throw error as don't support that source
  71. throw new TypeError('unsupported image source')
  72. }
  73. function makeRequest(url, resolve, reject, redirectCount, requestOptions) {
  74. const isHttps = url.protocol === 'https:'
  75. // lazy load the lib
  76. const lib = isHttps ? (!https ? (https = require('https')) : https) : !http ? (http = require('http')) : http
  77. lib
  78. .get(url.toString(), requestOptions || {}, (res) => {
  79. try {
  80. const shouldRedirect = REDIRECT_STATUSES.has(res.statusCode) && typeof res.headers.location === 'string'
  81. if (shouldRedirect && redirectCount > 0)
  82. return makeRequest(
  83. new URL(res.headers.location, url.origin),
  84. resolve,
  85. reject,
  86. redirectCount - 1,
  87. requestOptions,
  88. )
  89. if (typeof res.statusCode === 'number' && (res.statusCode < 200 || res.statusCode >= 300)) {
  90. return reject(new Error(`remote source rejected with status code ${res.statusCode}`))
  91. }
  92. consumeStream(res).then(resolve, reject)
  93. } catch (err) {
  94. reject(err)
  95. }
  96. })
  97. .on('error', reject)
  98. }
  99. // use stream/consumers in the future?
  100. function consumeStream(res) {
  101. return new Promise((resolve, reject) => {
  102. const chunks = []
  103. res.on('data', (chunk) => chunks.push(chunk))
  104. res.on('end', () => resolve(Buffer.concat(chunks)))
  105. res.on('error', reject)
  106. })
  107. }
  108. async function createImage(src, alt) {
  109. const image = new Image()
  110. if (typeof alt === 'string') image.alt = alt
  111. return new Promise((resolve, reject) => {
  112. image.onload = () => {
  113. // Wait for bitmap decode before resolving
  114. image.decode().then(() => resolve(image), reject)
  115. }
  116. image.onerror = (e) => reject(e)
  117. image.src = src
  118. })
  119. }
  120. function isBufferLike(src) {
  121. return (src && src.type === 'Buffer') || Array.isArray(src)
  122. }
  123. async function exists(path) {
  124. try {
  125. await fs.promises.access(path, fs.constants.F_OK)
  126. return true
  127. } catch {
  128. return false
  129. }
  130. }