For AI agents: the complete documentation index is available at https://anyformat.swc.rs/llms.txt, the full documentation bundle is available at https://anyformat.swc.rs/llms-full.txt, and this page is available as Markdown at https://anyformat.swc.rs/guide/migrate-from-pngjs-and-pixelmatch.md.

Migrate from pngjs and pixelmatch

Visual regression tools often use pngjs to read and write PNG files and pixelmatch to compare the pixels. @swc/anyformat-image replaces both packages:

  • The decoded pixels are the same as the pixels from pngjs 7.0.0, except for the differences in Decoding.
  • The diff count and the diff image are the same as the results of pixelmatch 8.0.0, 7.2.0, 6.0.0, or 5.3.0 with a Uint8Array output (see Differences from pixelmatch).
  • One call can decode two files, compare them, and encode the diff image.
  • Every function that decodes, encodes, or compares has an asynchronous form that does not block the event loop.

See the image API reference for the full API. The examples on this page use Node.js. In Python, use decode, encode, and compare_images. The options have the same names in snake case. Give encode options as PngEncodeOptions(...), PNG decode options as PngDecodeOptions(...), and the decode option of compare_images as DecodeOptions(...), not as dictionaries.

Compare two PNG files

With pngjs and pixelmatch:

import fs from 'node:fs'
import { PNG } from 'pngjs'
import pixelmatch from 'pixelmatch'

const img1 = PNG.sync.read(fs.readFileSync('expected.png'))
const img2 = PNG.sync.read(fs.readFileSync('actual.png'))
const { width, height } = img1
const diff = new PNG({ width, height })

const diffPixels = pixelmatch(img1.data, img2.data, diff.data, width, height, {
  threshold: 0.1,
})

fs.writeFileSync('diff.png', PNG.sync.write(diff))

With @swc/anyformat-image:

import fs from 'node:fs/promises'
import { compareImages } from '@swc/anyformat-image'

const result = await compareImages(
  await fs.readFile('expected.png'),
  await fs.readFile('actual.png'),
  { threshold: 0.1, diff: { format: 'png' } },
)

await fs.writeFile('diff.png', result.diffEncoded)

The pixels of the two files stay in native memory. To compare images that are already in memory, pass raw images. A pngjs PNG object is a valid raw image, so you can migrate one step at a time:

import { compareImagesSync } from '@swc/anyformat-image'

const result = compareImagesSync(img1, img2, { threshold: 0.1, diff: 'raw' })
result.diffPixels // the return value of pixelmatch
result.diffImage.data // the pixels that pixelmatch writes into the output

API mapping

pngjs and pixelmatch@swc/anyformat-image
PNG.sync.read(buf)decodeSync(buf) or await decode(buf)
PNG.sync.read(buf, { checkCRC: false })decodeSync(buf, { png: { checkCrc: false } })
png.gamma, png.interlace, png.alphadecoded.info.gamma, .interlaced, .hasAlpha
metadata eventreadImageInfo(buf)
new PNG({ width, height }){ width, height, data: Buffer.alloc(width * height * 4) }
PNG.sync.write(png)encodeSync(png, { format: 'png' }) (see PNG compression)
PNG.sync.write(png, { colorType: 2 })encodeSync(png, { format: 'png', colorType: 'rgb' })
PNG.sync.write(png, { colorType: 0 })encodeSync(png, { format: 'png', colorType: 'gray' })
PNG.sync.write(png, { colorType: 4 })encodeSync(png, { format: 'png', colorType: 'gray-alpha' })
bgColor: { red, green, blue }background: [red, green, blue]
deflateLevel: 0compression: 'none'
deflateLevel 1 to 9 with deflateStrategy: 3 (default)'balanced' (default) or 'fastest'; see PNG compression
deflateLevel: 1 with deflateStrategy: 0compression: 'fastest', filter: 'adaptive'
deflateLevel: 3 with deflateStrategy: 0compression: 'fast'
deflateLevel: 6 with deflateStrategy: 0compression: 'balanced'
deflateLevel: 9 with deflateStrategy: 0compression: 'high'
filterType: 4filter: 'paeth'
pixelmatch(a.data, b.data, null, w, h, opts)(await compareImages(a, b, opts)).diffPixels
pixelmatch(a.data, b.data, out.data, w, h, opts)(await compareImages(a, b, { ...opts, diff: 'raw' })).diffImage
pixelmatch(..., { windowSize: 16 })result.windowDiffPixels
pixelmatch 6 or 7 pinned in package.jsonalgorithm: 'pixelmatch6' or 'pixelmatch7'
PNG.sync.read twice, pixelmatch, PNG.sync.writecompareImages(bufA, bufB, { ...opts, diff: { format: 'png' } })

The comparison options have the same names and defaults as pixelmatch 8. The values are checked more strictly than in pixelmatch. See Compare options. An option that is null has its default value here, but pixelmatch uses null as the value: for example, threshold: null means 0 in pixelmatch.

pixelmatch draws only the pixels that differ when diffMask is set, and keeps the other bytes of the output buffer. diffImage is transparent at these pixels, so a program that fills the output first, for example with a copy of the first image, must draw the diff image over that copy itself.

These features of pngjs have no replacement:

  • The stream API (parse, pack, and the events), bitblt, and adjustGamma.
  • 16-bit output: skipRescale of PNG.sync.read and bitDepth: 16 of PNG.sync.write.
  • Input that is not RGBA: inputColorType and inputHasAlpha of PNG.sync.write.
  • Metadata on write: pngjs writes the gAMA chunk of png.gamma. encode writes no metadata.
  • deflateChunkSize, deflateFactory, the fill option of new PNG(), and png.palette.
  • The pixelmatch command-line tool.

png.depth maps to info.bitDepth, and png.colorType (a number) maps to info.colorType (a name, for example 'rgba').

Decoding

decode and pngjs give different results in these cases:

  • EXIF orientation. decode applies the orientation of an eXIf chunk by default, as browsers do, so the width and the height can change. pngjs ignores it. Pass orientation: 'ignore' to get the pixels of pngjs, also in the decode option of compareImages.
  • Gamma. pngjs sets png.gamma to 0 when the file has no gAMA chunk. info.gamma is null in this case. gamma, bitDepth, and the other PNG fields exist only when info.format is 'png'; check it first in TypeScript.
  • Chunks after the image data. pngjs applies a tRNS chunk that comes after the image data. decode ignores it, as the PNG specification requires, so the pixels that it makes transparent stay opaque.
  • Files that are not valid. pngjs rejects a bad CRC in the chunks that it reads, for example gAMA, tRNS, and IEND. decode checks the CRC of IHDR, PLTE, and IDAT only, and ignores an ancillary chunk with a bad CRC. See Conversion to rgba8 for the other cases.

PNG compression

The encoded bytes are not identical to the bytes of pngjs, because the deflate implementations are different. The decoded pixels are identical.

The default of pngjs is not comparable to a zlib level. pngjs uses deflateLevel: 9 with deflateStrategy: 3 (Z_RLE). With Z_RLE, zlib finds only matches at distance 1, and the level has almost no effect: levels 1 and 9 give the same file. So the pngjs default makes large files quickly.

  • Do not map the pngjs default to 'high'. 'high' is zlib level 9 with the default strategy. In the measurement below, it was about twice as slow as the pngjs default and made a file that was about 6 times smaller. The ratios depend on the image: on other images, 'high' was faster than the pngjs default, or not smaller than 'balanced'.
  • 'fastest' is much faster than the pngjs default (3.9 ms against 68.4 ms below), but its file can be larger than the file of pngjs, for example for line art. 'balanced' is usually smaller than the pngjs default. On images with large flat areas, the pngjs default can be smaller. Measure with your own images if the file size matters.
  • With deflateStrategy: 0, the levels in the table above are the same zlib levels. The files are not identical, because zlib-rs and the zlib of Node.js are different implementations. 'fastest' uses the 'up' filter by default, and pngjs selects the filter of each row. Add filter: 'adaptive' to select the filter of each row.

Performance

A measurement on one Apple Silicon Mac with Node.js 24, with one synthetic 1920 × 1080 screenshot and a changed copy. pngjs wrote the PNG input files. Both packages use one thread.

Operationpngjs and pixelmatch 8@swc/anyformat-image
Decode PNG33.0 ms8.3 ms
Encode PNG ('balanced')70.3 ms21.1 ms
Compare raw images with a diff image14.2 ms3.6 ms
Decode two files, compare, encode the diff132.0 ms41.1 ms

The diff counts were identical. pngjs writes with the RLE strategy, which gives many short matches and makes the inflate slow. A file from this encoder decodes in 2.6 ms; pngjs decodes the same file in 17 ms.

The encoder with each compression value:

compressionSizeTime
'fastest'468 KiB3.9 ms
'fast'254 KiB8.0 ms
'balanced'208 KiB21.9 ms
'high'175 KiB132.7 ms

pngjs with the same image. The time also includes the filters, which pngjs runs in JavaScript, so even the fastest setting takes 55 ms.

pngjs optionsSizeTime
Default (deflateLevel: 9, deflateStrategy: 3)1118 KiB68.4 ms
deflateLevel: 1, deflateStrategy: 31118 KiB68.8 ms
deflateLevel: 1, deflateStrategy: 0290 KiB55.0 ms
deflateLevel: 6, deflateStrategy: 0183 KiB83.8 ms
deflateLevel: 9, deflateStrategy: 0165 KiB311.1 ms

At the same zlib level and with the adaptive filter, @swc/anyformat-image was faster than pngjs: level 6 took 22 ms against 84 ms, and level 9 took 133 ms against 311 ms. On this image, its files were larger (208 KiB against 183 KiB, and 175 KiB against 165 KiB). On other images, they were smaller.