Home

Awesome

build codecov npm version

pngjs

Simple PNG encoder/decoder for Node.js with no dependencies.

Based on the original pngjs with the follow enhancements.

Known lack of support for:

Table of Contents

Comparison Table

NameForked FromSyncAsync16 Bit1/2/4 BitInterlaceGammaEncodesTested
pngjsYesYesYesYesYesYesYesYes
node-pngpngjsNoYesNoNoNoHiddenYesManual
png-coderpngjsNoYesYesNoNoHiddenYesManual
pngparseNoYesNoYesNoNoNoYes
pngparse-syncpngparseYesNoNoYesNoNoNoYes
png-asyncNoYesNoNoNoNoYesYes
png-jsNoYesNoNoNoNoNoNo

Native C++ node decoders:

Tests

Tested using PNG Suite. We read every file into pngjs, output it in standard 8bit colour, synchronously and asynchronously, then compare the original with the newly saved images.

To run the tests, fetch the repo (tests are not distributed via npm) and install with npm i, run npm test.

The only thing not converted is gamma correction - this is because multiple vendors will do gamma correction differently, so the tests will have different results on different browsers.

Installation

$ npm install pngjs  --save

Browser

The package has been build with a Browserify version (npm run browserify) and you can use the browser version by including in your code:

import { PNG } from 'pngjs/browser';

Example

var fs = require("fs"),
  PNG = require("pngjs").PNG;

fs.createReadStream("in.png")
  .pipe(
    new PNG({
      filterType: 4,
    })
  )
  .on("parsed", function () {
    for (var y = 0; y < this.height; y++) {
      for (var x = 0; x < this.width; x++) {
        var idx = (this.width * y + x) << 2;

        // invert color
        this.data[idx] = 255 - this.data[idx];
        this.data[idx + 1] = 255 - this.data[idx + 1];
        this.data[idx + 2] = 255 - this.data[idx + 2];

        // and reduce opacity
        this.data[idx + 3] = this.data[idx + 3] >> 1;
      }
    }

    this.pack().pipe(fs.createWriteStream("out.png"));
  });

For more examples see examples folder.

Async API

As input any color type is accepted (grayscale, rgb, palette, grayscale with alpha, rgb with alpha) but 8 bit per sample (channel) is the only supported bit depth. Interlaced mode is not supported.

Class: PNG

PNG is readable and writable Stream.

Options

Event "metadata"

function(metadata) { } Image's header has been parsed, metadata contains this information:

Event: "parsed"

function(data) { } Input image has been completely parsed, data is complete and ready for modification.

Event: "error"

function(error) { }

png.parse(data, [callback])

Parses PNG file data. Can be String or Buffer. Alternatively you can stream data to instance of PNG.

Optional callback is once called on error or parsed. The callback gets two arguments (err, data).

Returns this for method chaining.

Example

new PNG({ filterType: 4 }).parse(imageData, function (error, data) {
  console.log(error, data);
});

png.pack()

Starts converting data to PNG file Stream.

Returns this for method chaining.

png.bitblt(dst, sx, sy, w, h, dx, dy)

Helper for image manipulation, copies a rectangle of pixels from current (i.e. the source) image (sx, sy, w, h) to dst image (at dx, dy).

Returns this for method chaining.

For example, the following code copies the top-left 100x50 px of in.png into dst and writes it to out.png:

var dst = new PNG({ width: 100, height: 50 });
fs.createReadStream("in.png")
  .pipe(new PNG())
  .on("parsed", function () {
    this.bitblt(dst, 0, 0, 100, 50, 0, 0);
    dst.pack().pipe(fs.createWriteStream("out.png"));
  });

Property: adjustGamma()

Helper that takes data and adjusts it to be gamma corrected. Note that it is not 100% reliable with transparent colours because that requires knowing the background colour the bitmap is rendered on to.

In tests against PNG suite it compared 100% with chrome on all 8 bit and below images. On IE there were some differences.

The following example reads a file, adjusts the gamma (which sets the gamma to 0) and writes it out again, effectively removing any gamma correction from the image.

fs.createReadStream("in.png")
  .pipe(new PNG())
  .on("parsed", function () {
    this.adjustGamma();
    this.pack().pipe(fs.createWriteStream("out.png"));
  });

Property: width

Width of image in pixels

Property: height

Height of image in pixels

Property: data

Buffer of image pixel data. Every pixel consists 4 bytes: R, G, B, A (opacity).

Property: gamma

Gamma of image (0 if not specified)

Packing a PNG and removing alpha (RGBA to RGB)

When removing the alpha channel from an image, there needs to be a background color to correctly convert each pixel's transparency to the appropriate RGB value. By default, pngjs will flatten the image against a white background. You can override this in the options:

var fs = require("fs"),
  PNG = require("pngjs").PNG;

fs.createReadStream("in.png")
  .pipe(
    new PNG({
      colorType: 2,
      bgColor: {
        red: 0,
        green: 255,
        blue: 0,
      },
    })
  )
  .on("parsed", function () {
    this.pack().pipe(fs.createWriteStream("out.png"));
  });

Sync API

PNG.sync

PNG.sync.read(buffer)

Take a buffer and returns a PNG image. The properties on the image include the meta data and data as per the async API above.

var data = fs.readFileSync('in.png');
var png = PNG.sync.read(data);

PNG.sync.write(png)

Take a PNG image and returns a buffer. The properties on the image include the meta data and data as per the async API above.

var data = fs.readFileSync('in.png');
var png = PNG.sync.read(data);
var options = { colorType: 6 };
var buffer = PNG.sync.write(png, options);
fs.writeFileSync('out.png', buffer);

PNG.adjustGamma(src)

Adjusts the gamma of a sync image. See the async adjustGamma.

var data = fs.readFileSync('in.png');
var png = PNG.sync.read(data);
PNG.adjustGamma(png);