UNPKG

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