Registry / serialization / pngjs
library7.0.0jsnpmunverified

pngjs is a pure JavaScript library for encoding and decoding PNG images, primarily designed for Node.js environments but also usable in browsers via Browserify. It offers both synchronous and asynchronous APIs, supporting a wide range of PNG bit depths (1, 2, 4, 8, 16-bit) and interlace types for reading. The library distinguishes itself by having no external dependencies, providing a lightweight solution for image manipulation. The current stable version is 7.0.0. While it supports reading various color types and bit depths, its asynchronous writing API primarily processes 8-bit per sample (channel) images and does not support interlaced mode for output. It can read `tTRNS` transparent colors and supports writing colortype 0 (grayscale), 2 (RGB), 4 (grayscale alpha), and 6 (RGBA), but currently lacks support for extended PNG features like animation and writing indexed color (colortype 3). Its API is compatible with older `pngjs` and `node-pngjs` implementations, and it is rigorously tested against the PNG Suite.

npm install pngjs
INSTALL
IMPORT
SIG · PNGJS
P
pngjs
serializationjavascriptv7.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

PNG
import { PNG } from 'pngjs';
const PNG = require('pngjs');
For CommonJS, prefer `const { PNG } = require('pngjs');`. For ES Modules or TypeScript, use named import.
PNG (CommonJS)
const { PNG } = require('pngjs');
import { PNG } from 'pngjs';
This is the idiomatic CommonJS way to import the PNG class. The legacy `require('pngjs').PNG` also works.
PNG (Browser)
import { PNG } from 'pngjs/browser';
Use this specific path when bundling for browser environments to ensure correct build optimization.

This example demonstrates how to read a PNG file, manipulate its pixel data (inverting colors and reducing opacity), and then write the modified image to a new PNG file using the `pngjs` asynchronous API. It includes a small dummy PNG creation for immediate runnable testing.

import { createReadStream, createWriteStream } from 'fs'; import { PNG } from 'pngjs'; // Create a dummy PNG file for the example if it doesn't exist const dummyPngData = Buffer.from([ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82 ]); createWriteStream('in.png').write(dummyPngData, () => { console.log('Dummy in.png created.'); createReadStream('in.png') .pipe( new PNG({ filterType: 4 }) ) .on('parsed', function () { console.log('PNG parsed. Image dimensions:', this.width, 'x', this.height); for (let y = 0; y < this.height; y++) { for (let x = 0; x < this.width; x++) { const idx = (this.width * y + x) << 2; // Invert color this.data[idx] = 255 - this.data[idx]; // R this.data[idx + 1] = 255 - this.data[idx + 1]; // G this.data[idx + 2] = 255 - this.data[idx + 2]; // B // Reduce opacity by half this.data[idx + 3] = this.data[idx + 3] >> 1; // A } } console.log('Image data modified. Packing...'); this.pack().pipe(createWriteStream('out.png')) .on('finish', () => console.log('Generated out.png with inverted colors and reduced opacity.')); }) .on('error', (err) => { console.error('Error during PNG parsing:', err.message); }); });
Debug
Known issues
gotchapngjs does not support Extended PNG features, such as animation (e.g., APNG). Attempts to parse or write such files may result in unexpected behavior or errors.
fix
For advanced features like animation, consider alternative libraries designed for specific extended PNG formats.
affects: >=1.0.0
gotchaWhen writing PNG files, pngjs currently lacks support for Color Type 3 (indexed color). Users must convert image data to one of the supported color types (grayscale, RGB, grayscale alpha, RGBA) before writing.
fix
Ensure your image data is in a supported color type (0, 2, 4, or 6) before initiating the write operation. Pre-process your pixel data if it originates from an indexed color source.
affects: >=1.0.0
gotchaWhile pngjs can read and handle various bit depths (1, 2, 4, 8, 16 bit) and interlace types, the asynchronous writing API only supports 8-bit per sample (channel) output and does not support interlaced mode for output. Input images with higher bit depths or interlace will be converted to 8-bit non-interlaced upon output.
fix
Be aware that images with characteristics beyond 8-bit per sample and non-interlaced will be converted to this standard upon writing with the async API. For specific control over higher bit depths or interlace in output, direct pixel manipulation might be needed, or consider the sync API if it supports more options.
affects: >=1.0.0
gotchaGamma correction handling can vary between different image viewers, browsers, and operating systems. pngjs processes raw pixel data, and differences in gamma interpretation can lead to subtle visual discrepancies when the same image is viewed across different platforms.
fix
If precise visual fidelity across all platforms is critical, ensure consistent gamma correction settings or consider pre-processing images to a standard gamma value, understanding that different display environments may still apply their own corrections.
affects: >=1.0.0
Errors
Common errors & fixes
ReferenceError: require is not defined
Attempting to use CommonJS `require()` syntax in an ES Module context (e.g., when 'type: "module"' is set in `package.json` or in a `.mjs` file).
fix
Change the import statement to `import { PNG } = from 'pngjs';` for ES Modules.
Error: Unsupported color type
Trying to write an image with a color type that pngjs does not support for output, such as Color Type 3 (indexed color).
fix
Ensure that the `colortype` option passed to the PNG constructor (if creating a new PNG) or the image data being packed corresponds to a supported output type (grayscale, RGB, grayscale alpha, RGBA).
TypeError: Cannot read properties of undefined (reading 'height')
This typically occurs within the `on('parsed')` event handler when the input stream either failed to parse a valid PNG, or the stream piping was interrupted, leading to an incomplete or corrupted `this` (PNG object).
fix
Verify that the input file (`in.png` in examples) is a valid, non-corrupted PNG image. Add robust error handling to the `createReadStream` and `pipe` operations to catch issues earlier (e.g., `createReadStream('in.png').on('error', handleError)`).
Upgrade
Version history
7.0.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
24 hits · last 30 days
node
22
Resources
pngjs — npm install pngjs · libregistry