MCPcopy Create free account
hub / github.com/heygen-com/hyperframes / decodePngRaw

Function decodePngRaw

packages/engine/src/utils/alphaBlit.ts:31–149  ·  view source on GitHub ↗

* Shared PNG chunk parsing + filter reconstruction. * * Verifies the PNG signature, iterates chunks to collect IHDR metadata and IDAT * payloads, decompresses with zlib, and reconstructs all 5 PNG filter types. * * Returns the defiltered pixel bytes (no filter-type prefix bytes) along with * I

(
  buf: Buffer,
  caller: string,
)

Source from the content-addressed store, hash-verified

29 * IHDR fields so callers can convert to their target pixel format.
30 */
31function decodePngRaw(
32 buf: Buffer,
33 caller: string,
34): { width: number; height: number; bitDepth: number; colorType: number; rawPixels: Buffer } {
35 // Verify PNG signature
36 if (
37 buf[0] !== 137 ||
38 buf[1] !== 80 ||
39 buf[2] !== 78 ||
40 buf[3] !== 71 ||
41 buf[4] !== 13 ||
42 buf[5] !== 10 ||
43 buf[6] !== 26 ||
44 buf[7] !== 10
45 ) {
46 throw new Error(`${caller}: not a PNG file`);
47 }
48
49 let pos = 8;
50 let width = 0;
51 let height = 0;
52 let bitDepth = 0;
53 let colorType = 0;
54 let interlace = 0;
55 let sawIhdr = false;
56 const idatChunks: Buffer[] = [];
57
58 while (pos + 12 <= buf.length) {
59 const chunkLen = buf.readUInt32BE(pos);
60 const chunkType = buf.toString("ascii", pos + 4, pos + 8);
61 const chunkData = buf.subarray(pos + 8, pos + 8 + chunkLen);
62
63 if (chunkType === "IHDR") {
64 width = chunkData.readUInt32BE(0);
65 height = chunkData.readUInt32BE(4);
66 bitDepth = chunkData[8] ?? 0;
67 colorType = chunkData[9] ?? 0;
68 interlace = chunkData[12] ?? 0;
69 sawIhdr = true;
70 } else if (chunkType === "IDAT") {
71 idatChunks.push(Buffer.from(chunkData));
72 } else if (chunkType === "IEND") {
73 break;
74 }
75
76 pos += 12 + chunkLen; // length(4) + type(4) + data(chunkLen) + crc(4)
77 }
78
79 if (!sawIhdr) {
80 throw new Error(`${caller}: PNG missing IHDR chunk`);
81 }
82 if (colorType !== 2 && colorType !== 6) {
83 throw new Error(`${caller}: unsupported color type ${colorType} (expected 2=RGB or 6=RGBA)`);
84 }
85 if (interlace !== 0) {
86 throw new Error(
87 `${caller}: Adam7-interlaced PNGs are not supported (interlace method ${interlace})`,
88 );

Callers 2

decodePngFunction · 0.85
decodePngToRgb48leFunction · 0.85

Calls 3

paethFunction · 0.85
fromMethod · 0.80
setMethod · 0.65

Tested by

no test coverage detected