png.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. var fs = require('fs')
  2. var PNG = require('pngjs').PNG
  3. var Utils = require('./utils')
  4. exports.render = function render (qrData, options) {
  5. var opts = Utils.getOptions(options)
  6. var pngOpts = opts.rendererOpts
  7. var size = Utils.getImageWidth(qrData.modules.size, opts)
  8. pngOpts.width = size
  9. pngOpts.height = size
  10. var 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. var 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. var png = exports.render(qrData, options)
  32. var 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. var stream = fs.createWriteStream(path)
  48. stream.on('error', cb)
  49. stream.on('close', cb)
  50. exports.renderToFileStream(stream, qrData, options)
  51. }
  52. exports.renderToFileStream = function renderToFileStream (stream, qrData, options) {
  53. var png = exports.render(qrData, options)
  54. png.pack().pipe(stream)
  55. }