packer-sync.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. "use strict";
  2. let hasSyncZlib = true;
  3. let zlib = require("zlib");
  4. if (!zlib.deflateSync) {
  5. hasSyncZlib = false;
  6. }
  7. let constants = require("./constants");
  8. let Packer = require("./packer");
  9. module.exports = function (metaData, opt) {
  10. if (!hasSyncZlib) {
  11. throw new Error(
  12. "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0"
  13. );
  14. }
  15. let options = opt || {};
  16. let packer = new Packer(options);
  17. let chunks = [];
  18. // Signature
  19. chunks.push(Buffer.from(constants.PNG_SIGNATURE));
  20. // Header
  21. chunks.push(packer.packIHDR(metaData.width, metaData.height));
  22. if (metaData.gamma) {
  23. chunks.push(packer.packGAMA(metaData.gamma));
  24. }
  25. let filteredData = packer.filterData(
  26. metaData.data,
  27. metaData.width,
  28. metaData.height
  29. );
  30. // compress it
  31. let compressedData = zlib.deflateSync(
  32. filteredData,
  33. packer.getDeflateOptions()
  34. );
  35. filteredData = null;
  36. if (!compressedData || !compressedData.length) {
  37. throw new Error("bad png - invalid compressed data response");
  38. }
  39. chunks.push(packer.packIDAT(compressedData));
  40. // End
  41. chunks.push(packer.packIEND());
  42. return Buffer.concat(chunks);
  43. };