png.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const fs = require('fs')
  2. const PNG = require('pngjs').PNG
  3. const Utils = require('./utils')
  4. exports.render = function render (qrData, options) {
  5. const opts = Utils.getOptions(options)
  6. const pngOpts = opts.rendererOpts
  7. const size = Utils.getImageWidth(qrData.modules.size, opts)
  8. pngOpts.width = size
  9. pngOpts.height = size
  10. const pngImage = new PNG(pngOpts)
  11. Utils.qrToImageData(pngImage.data, qrData, opts)
  12. return pngImage
  13. }
  14. exports.renderToDataURL = function renderToDataURL (qrData, options, cb) {
  15. if (typeof cb === 'undefined') {
  16. cb = options
  17. options = undefined
  18. }
  19. exports.renderToBuffer(qrData, options, function (err, output) {
  20. if (err) cb(err)
  21. let url = 'data:image/png;base64,'
  22. url += output.toString('base64')
  23. cb(null, url)
  24. })
  25. }
  26. exports.renderToBuffer = function renderToBuffer (qrData, options, cb) {
  27. if (typeof cb === 'undefined') {
  28. cb = options
  29. options = undefined
  30. }
  31. const png = exports.render(qrData, options)
  32. const buffer = []
  33. png.on('error', cb)
  34. png.on('data', function (data) {
  35. buffer.push(data)
  36. })
  37. png.on('end', function () {
  38. cb(null, Buffer.concat(buffer))
  39. })
  40. png.pack()
  41. }
  42. exports.renderToFile = function renderToFile (path, qrData, options, cb) {
  43. if (typeof cb === 'undefined') {
  44. cb = options
  45. options = undefined
  46. }
  47. let called = false
  48. const done = (...args) => {
  49. if (called) return
  50. called = true
  51. cb.apply(null, args)
  52. }
  53. const stream = fs.createWriteStream(path)
  54. stream.on('error', done)
  55. stream.on('close', done)
  56. exports.renderToFileStream(stream, qrData, options)
  57. }
  58. exports.renderToFileStream = function renderToFileStream (stream, qrData, options) {
  59. const png = exports.render(qrData, options)
  60. png.pack().pipe(stream)
  61. }