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 pngjsVerified import paths — ran on the pinned version, not inferred.
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.
For advanced features like animation, consider alternative libraries designed for specific extended PNG formats.
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.
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.
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.
Change the import statement to `import { PNG } = from 'pngjs';` for ES Modules.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).
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)`).No dependency data recorded yet.