pngstream.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. /*!
  3. * Canvas - PNGStream
  4. * Copyright (c) 2010 LearnBoost <tj@learnboost.com>
  5. * MIT Licensed
  6. */
  7. /**
  8. * Module dependencies.
  9. */
  10. var Stream = require('stream').Stream;
  11. /**
  12. * Initialize a `PNGStream` with the given `canvas`.
  13. *
  14. * "data" events are emitted with `Buffer` chunks, once complete the
  15. * "end" event is emitted. The following example will stream to a file
  16. * named "./my.png".
  17. *
  18. * var out = fs.createWriteStream(__dirname + '/my.png')
  19. * , stream = canvas.createPNGStream();
  20. *
  21. * stream.pipe(out);
  22. *
  23. * @param {Canvas} canvas
  24. * @param {Boolean} sync
  25. * @api public
  26. */
  27. var PNGStream = module.exports = function PNGStream(canvas, sync) {
  28. var self = this
  29. , method = sync
  30. ? 'streamPNGSync'
  31. : 'streamPNG';
  32. this.sync = sync;
  33. this.canvas = canvas;
  34. this.readable = true;
  35. // TODO: implement async
  36. if ('streamPNG' == method) method = 'streamPNGSync';
  37. process.nextTick(function(){
  38. canvas[method](function(err, chunk, len){
  39. if (err) {
  40. self.emit('error', err);
  41. self.readable = false;
  42. } else if (len) {
  43. self.emit('data', chunk, len);
  44. } else {
  45. self.emit('end');
  46. self.readable = false;
  47. }
  48. });
  49. });
  50. };
  51. /**
  52. * Inherit from `EventEmitter`.
  53. */
  54. PNGStream.prototype.__proto__ = Stream.prototype;