packer-async.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. let util = require("util");
  3. let Stream = require("stream");
  4. let constants = require("./constants");
  5. let Packer = require("./packer");
  6. let PackerAsync = (module.exports = function (opt) {
  7. Stream.call(this);
  8. let 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", Buffer.from(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. let filteredData = this._packer.filterData(data, width, height);
  22. // compress it
  23. this._deflate.on("error", this.emit.bind(this, "error"));
  24. this._deflate.on(
  25. "data",
  26. function (compressedData) {
  27. this.emit("data", this._packer.packIDAT(compressedData));
  28. }.bind(this)
  29. );
  30. this._deflate.on(
  31. "end",
  32. function () {
  33. this.emit("data", this._packer.packIEND());
  34. this.emit("end");
  35. }.bind(this)
  36. );
  37. this._deflate.end(filteredData);
  38. };