jpegstream.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. /*!
  3. * Canvas - JPEGStream
  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 `JPEGStream` 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.jpeg".
  17. *
  18. * var out = fs.createWriteStream(__dirname + '/my.jpeg')
  19. * , stream = canvas.createJPEGStream();
  20. *
  21. * stream.pipe(out);
  22. *
  23. * @param {Canvas} canvas
  24. * @param {Boolean} sync
  25. * @api public
  26. */
  27. var JPEGStream = module.exports = function JPEGStream(canvas, options, sync) {
  28. var self = this
  29. , method = sync
  30. ? 'streamJPEGSync'
  31. : 'streamJPEG';
  32. this.options = options;
  33. this.sync = sync;
  34. this.canvas = canvas;
  35. this.readable = true;
  36. // TODO: implement async
  37. if ('streamJPEG' == method) method = 'streamJPEGSync';
  38. process.nextTick(function(){
  39. canvas[method](options.bufsize, options.quality, options.progressive, function(err, chunk){
  40. if (err) {
  41. self.emit('error', err);
  42. self.readable = false;
  43. } else if (chunk) {
  44. self.emit('data', chunk);
  45. } else {
  46. self.emit('end');
  47. self.readable = false;
  48. }
  49. });
  50. });
  51. };
  52. /**
  53. * Inherit from `EventEmitter`.
  54. */
  55. JPEGStream.prototype.__proto__ = Stream.prototype;