Fast PNG Encoder/Decoder

8.0.0 · active · verified Sun Apr 19

fast-png is a performant JavaScript library for encoding and decoding PNG image data, built entirely in JavaScript without native dependencies. The current stable version is 8.0.0, released in December 2025. This package focuses on speed, demonstrated by its recent switch to the `fflate` library for compression in v8.0.0. Major versions are released periodically (roughly annually), often introducing significant breaking changes like the migration to ESM in v7.0.0. It differentiates itself by offering a pure JavaScript implementation suitable for both Node.js and browser environments, while providing granular control over encoding options and supporting various PNG features like `tEXt` chunks, `tRNS` fields, and `ICC` profiles.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart encodes a simple 2x2 red image with metadata and then decodes it, verifying the pixel data and metadata.

import { decode, encode } from 'fast-png';

async function runPngExample() {
  // 1. Define a simple 2x2 red image in RGBA format
  const width = 2;
  const height = 2;
  const data = new Uint8Array([
    255, 0, 0, 255, // Red pixel 1
    255, 0, 0, 255, // Red pixel 2
    255, 0, 0, 255, // Red pixel 3
    255, 0, 0, 255  // Red pixel 4
  ]);

  // 2. Encode the image into a PNG buffer
  const encodedPngBuffer = encode({
    width,
    height,
    data,
    channels: 4, // RGBA
    depth: 8,    // 8 bits per channel
    text: { title: 'Test Image', author: 'AI' } // Optional tEXt chunks
  });

  console.log(`Encoded PNG buffer size: ${encodedPngBuffer.length} bytes`);

  // 3. Decode the PNG buffer back into an image object
  // For Node.js, the buffer output by encode is compatible with decode.
  // For browser, you might get an ArrayBuffer and need to wrap in Uint8Array.
  const decodedImage = decode(encodedPngBuffer, { checkCrc: true });

  console.log(`\n--- Decoded Image Information ---`);
  console.log(`Width: ${decodedImage.width}`);
  console.log(`Height: ${decodedImage.height}`);
  console.log(`Channels: ${decodedImage.channels}`);
  console.log(`Depth: ${decodedImage.depth}`);
  console.log(`Data length: ${decodedImage.data.length}`);
  console.log(`Text chunks:`, decodedImage.text);

  // 4. Verify a pixel value from the decoded data
  const firstPixelOffset = 0; // RGBA
  const [r, g, b, a] = decodedImage.data.slice(firstPixelOffset, firstPixelOffset + 4);
  console.log(`First pixel (R,G,B,A): (${r}, ${g}, ${b}, ${a})`);

  if (r === 255 && g === 0 && b === 0 && a === 255) {
    console.log('Successfully decoded the red pixel as expected!');
  } else {
    console.error('Decoded pixel color mismatch!');
  }
}

runPngExample().catch(console.error);

view raw JSON →