packer-sync.js 1.1 KB

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