packer-async.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. var util = require('util');
  3. var Stream = require('stream');
  4. var constants = require('./constants');
  5. var Packer = require('./packer');
  6. var PackerAsync = module.exports = function(opt) {
  7. Stream.call(this);
  8. var options = opt || {};
  9. this._packer = new Packer(options);
  10. this._deflate = this._packer.createDeflate();
  11. this.readable = true;
  12. };
  13. util.inherits(PackerAsync, Stream);
  14. PackerAsync.prototype.pack = function(data, width, height, gamma) {
  15. // Signature
  16. this.emit('data', new Buffer(constants.PNG_SIGNATURE));
  17. this.emit('data', this._packer.packIHDR(width, height));
  18. if (gamma) {
  19. this.emit('data', this._packer.packGAMA(gamma));
  20. }
  21. var filteredData = this._packer.filterData(data, width, height);
  22. // compress it
  23. this._deflate.on('error', this.emit.bind(this, 'error'));
  24. this._deflate.on('data', function(compressedData) {
  25. this.emit('data', this._packer.packIDAT(compressedData));
  26. }.bind(this));
  27. this._deflate.on('end', function() {
  28. this.emit('data', this._packer.packIEND());
  29. this.emit('end');
  30. }.bind(this));
  31. this._deflate.end(filteredData);
  32. };