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/node/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. To migrate from pixelmatch-py, read Migrate from pixelmatch-py.

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)

When the program also needs the pixels of the two files, for example to draw a composite of the two images and the diff, add decoded: true. The result then has the decoded pixels in decodedA and decodedB, so the program does not decode the files again. See Decoded inputs.

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' } })
PNG.sync.read twice, pixelmatch with an outputcompareImages(bufA, bufB, { ...opts, diff: 'raw', decoded: true })

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 pngjs levels in the chart below 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 used one thread. Since this measurement, compareImages uses all CPU cores (see Asynchronous calls and threads), so the two comparisons can be faster on a computer with more than one core.

Time of each operation with one 1920 × 1080 screenshot

Shorter is faster. Each operation has its own scale.

Decode PNG
Encode PNG ('balanced')
Compare raw images with a diff image
Decode two files, compare, encode the diff
Show the data as a table
OperationPackageTime
Decode PNGpngjs33.0 ms
Decode PNG@swc/anyformat-image8.3 ms
Encode PNG ('balanced')pngjs70.3 ms
Encode PNG ('balanced')@swc/anyformat-image21.1 ms
Compare raw images with a diff imagepixelmatch 814.2 ms
Compare raw images with a diff image@swc/anyformat-image3.6 ms
Decode two files, compare, encode the diffpngjs and pixelmatch 8132.0 ms
Decode two files, compare, encode the diff@swc/anyformat-image41.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 size and the encode time of each compression value and of pngjs with some options, with the same image. For pngjs, the time also includes the filters, which pngjs runs in JavaScript, so even the fastest setting takes 55 ms. RLE is deflateStrategy: 3. The other pngjs points use deflateStrategy: 0.

PNG encoder: file size against encode time

Lower and further left is better.

Size (KiB)
0
300
600
900
1200
2
5
10
20
50
100
200
500
Time (ms, logarithmic scale)
Show the data as a table
PackageSettingSizeTime
@swc/anyformat-imagecompression: 'fastest'468 KiB3.9 ms
@swc/anyformat-imagecompression: 'fast'254 KiB8.0 ms
@swc/anyformat-imagecompression: 'balanced'208 KiB21.9 ms
@swc/anyformat-imagecompression: 'high'175 KiB132.7 ms
pngjsdefault (deflateLevel: 9, deflateStrategy: 3)1118 KiB68.4 ms
pngjsdeflateLevel: 1, deflateStrategy: 31118 KiB68.8 ms
pngjsdeflateLevel: 1, deflateStrategy: 0290 KiB55.0 ms
pngjsdeflateLevel: 6, deflateStrategy: 0183 KiB83.8 ms
pngjsdeflateLevel: 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.