### Install pixelmatch with NPM Source: https://github.com/mapbox/pixelmatch/blob/main/README.md Installs the pixelmatch library using the Node Package Manager. ```bash npm install pixelmatch ``` -------------------------------- ### Compare Images Using Browser Canvas API Source: https://context7.com/mapbox/pixelmatch/llms.txt This example shows how to use pixelmatch directly with browser `ImageData` objects obtained from a `CanvasRenderingContext2D`. It requires no Node.js or file-system APIs. ```javascript import pixelmatch from 'https://esm.run/pixelmatch'; async function compareImages(urlA, urlB, canvasDiff) { const [bitmapA, bitmapB] = await Promise.all([ createImageBitmap(await (await fetch(urlA)).blob()), createImageBitmap(await (await fetch(urlB)).blob()), ]); const width = bitmapA.width; const height = bitmapA.height; // Draw each image to an offscreen canvas to extract pixel data const offscreen = (bitmap) => { const c = new OffscreenCanvas(width, height); const ctx = c.getContext('2d'); ctx.drawImage(bitmap, 0, 0); return ctx.getImageData(0, 0, width, height); }; const imgData1 = offscreen(bitmapA); const imgData2 = offscreen(bitmapB); // Prepare output canvas canvasDiff.width = width; canvasDiff.height = height; const diffCtx = canvasDiff.getContext('2d'); const diffData = diffCtx.createImageData(width, height); const numDiff = pixelmatch( imgData1.data, imgData2.data, diffData.data, width, height, { threshold: 0.1 } ); diffCtx.putImageData(diffData, 0, 0); console.log(`Different pixels: ${numDiff}`); return numDiff; } // Usage: // const diffCount = await compareImages('baseline.png', 'current.png', document.getElementById('diff-canvas')); ``` -------------------------------- ### Count-Only Mode Source: https://context7.com/mapbox/pixelmatch/llms.txt Perform a comparison without generating a diff output file. This mode is useful for quickly getting a difference count and error percentage, often used in automated checks. ```bash pixelmatch baseline.png current.png # different pixels: 143 # error: 0.09% ``` -------------------------------- ### Count Mismatched Pixels Only with pixelmatch Source: https://context7.com/mapbox/pixelmatch/llms.txt Pass `null` as the output buffer to skip generating a visual diff and only get the pixel mismatch count. This is faster when visual output is not needed, such as in CI checks. ```javascript import fs from '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; // Pass null — no diff image is generated const mismatch = pixelmatch(img1.data, img2.data, null, width, height, { threshold: 0.1 }); if (mismatch > 0) { console.error(`Visual regression detected: ${mismatch} pixels differ.`); process.exit(1); } console.log('Images match.'); // Images match. ``` -------------------------------- ### Compare PNG Files from Command Line Source: https://context7.com/mapbox/pixelmatch/llms.txt The `pixelmatch` CLI tool allows direct comparison of PNG files from the shell. It exits with specific codes for success, differences, or errors. ```bash # Install globally or use via npx npm install -g pixelmatch # Basic comparison — prints diff pixel count and error percentage pixelmatch baseline.png current.png diff.png # matched in: 12.345ms # different pixels: 143 # error: 0.09% ``` -------------------------------- ### pixelmatch Command Line Usage Source: https://github.com/mapbox/pixelmatch/blob/main/README.md Compares two PNG images using the pixelmatch binary and outputs the difference to a third PNG file. The last argument is the threshold. ```bash pixelmatch image1.png image2.png output.png 0.1 ``` -------------------------------- ### `pixelmatch` with `diffColorAlt` Source: https://context7.com/mapbox/pixelmatch/llms.txt Demonstrates using `diffColorAlt` to distinguish between pixels that became lighter or darker, useful for identifying added vs. removed content. ```APIDOC ## `pixelmatch` with `diffColorAlt` ### Description When `diffColorAlt` is set, pixels that become darker from `img1` to `img2` are drawn using `diffColorAlt`, while pixels that become lighter use the standard `diffColor`. This lets you visually distinguish "removed" content from "added" content in the diff output. ### Parameters - **img1** (Uint8Array | Uint8ClampedArray | Buffer) - The first RGBA image buffer. - **img2** (Uint8Array | Uint8ClampedArray | Buffer) - The second RGBA image buffer. - **output** (Uint8Array | Uint8ClampedArray | Buffer) - A buffer to receive the visual diff image. - **width** (number) - The width of the images. - **height** (number) - The height of the images. - **options** (object) - An object for tuning sensitivity and appearance. - **threshold** (number) - Sensitivity threshold for pixel comparison. - **diffColor** (Array) - RGB color for pixels that got lighter (added). - **diffColorAlt** (Array) - RGB color for pixels that got darker (removed). ### Request Example ```javascript import fs from 'fs'; import { PNG } from 'pngjs'; import pixelmatch from 'pixelmatch'; const img1 = PNG.sync.read(fs.readFileSync('before.png')); const img2 = PNG.sync.read(fs.readFileSync('after.png')); const { width, height } = img1; const diff = new PNG({ width, height }); const numDiffPixels = pixelmatch(img1.data, img2.data, diff.data, width, height, { threshold: 0.05, diffColor: [255, 0, 0], // red = pixels that got lighter (added) diffColorAlt: [0, 255, 0], // green = pixels that got darker (removed) }); fs.writeFileSync('diff-alt.png', PNG.sync.write(diff)); console.log(`Changed pixels: ${numDiffPixels}`); ``` ### Response Example (The function returns a number representing the count of differing pixels. The `output` buffer is modified in place.) ``` -------------------------------- ### Compare Images and Generate Diff with pixelmatch Source: https://context7.com/mapbox/pixelmatch/llms.txt Compares two RGBA images and generates a visual diff. Load images using `pngjs`, then pass their data buffers to `pixelmatch`. The `output` buffer receives the diff image, with options to control sensitivity, anti-aliasing detection, and diff colors. Exits with a non-zero status code if differences are found, useful for CI. ```javascript import fs from 'fs'; import { PNG } from 'pngjs'; import pixelmatch from 'pixelmatch'; // Load two PNG images of equal dimensions const img1 = PNG.sync.read(fs.readFileSync('screenshot-baseline.png')); const img2 = PNG.sync.read(fs.readFileSync('screenshot-current.png')); const { width, height } = img1; if (img2.width !== width || img2.height !== height) { throw new Error(`Dimension mismatch: ${width}x${height} vs ${img2.width}x${img2.height}`); } // Create an output PNG to hold the visual diff const diff = new PNG({ width, height }); const numDiffPixels = pixelmatch( img1.data, img2.data, diff.data, width, height, { threshold: 0.1, // default; 0 = exact match required, 1 = accept almost anything includeAA: false, // default; true = count anti-aliased pixels as differences alpha: 0.1, // opacity of unchanged background pixels in diff image aaColor: [255, 255, 0], // yellow highlights for anti-aliased pixels diffColor: [255, 0, 0], // red highlights for true pixel differences diffColorAlt: null, // optional second color for dark-on-light differences diffMask: false, // if true, outputs diff over transparent background checkerboard: true, // blend semi-transparent pixels against a checkerboard } ); fs.writeFileSync('diff.png', PNG.sync.write(diff)); const errorPercent = (100 * numDiffPixels / (width * height)).toFixed(2); console.log(`Different pixels: ${numDiffPixels}`); console.log(`Error: ${errorPercent}%`); // Different pixels: 143 // Error: 0.09% // Exit non-zero when images differ (useful in CI) process.exit(numDiffPixels ? 1 : 0); ``` -------------------------------- ### `pixelmatch(img1, img2, output, width, height[, options])` Source: https://context7.com/mapbox/pixelmatch/llms.txt Compares two RGBA images pixel by pixel using perceptual color difference (YIQ) and anti-aliasing detection. Returns the number of differing pixels. The `output` buffer, if provided, is written with a visual diff image. ```APIDOC ## `pixelmatch(img1, img2, output, width, height[, options])` ### Description Compares two RGBA images pixel by pixel using perceptual color difference (YIQ) and anti-aliasing detection. Returns the number of differing pixels. The `output` buffer, if provided, is written with a visual diff image: unchanged pixels are drawn as a dimmed grayscale version of `img1`, anti-aliased pixels in yellow, and true differences in red (or the configured diff colors). ### Parameters - **img1** (Uint8Array | Uint8ClampedArray | Buffer) - The first RGBA image buffer. - **img2** (Uint8Array | Uint8ClampedArray | Buffer) - The second RGBA image buffer. - **output** (Uint8Array | Uint8ClampedArray | Buffer | null) - An optional buffer to receive the visual diff image. If null, no diff image is generated. - **width** (number) - The width of the images. - **height** (number) - The height of the images. - **options** (object, optional) - An object for tuning sensitivity and appearance. - **threshold** (number) - Default: 0.1. 0 = exact match required, 1 = accept almost anything. - **includeAA** (boolean) - Default: false. If true, count anti-aliased pixels as differences. - **alpha** (number) - Default: 0.1. Opacity of unchanged background pixels in diff image. - **aaColor** (Array) - Default: [255, 255, 0]. Yellow highlights for anti-aliased pixels (RGB). - **diffColor** (Array) - Default: [255, 0, 0]. Red highlights for true pixel differences (RGB). - **diffColorAlt** (Array | null) - Optional second color for dark-on-light differences (RGB). - **diffMask** (boolean) - Default: false. If true, outputs diff over transparent background. - **checkerboard** (boolean) - Default: true. Blend semi-transparent pixels against a checkerboard. ### Returns - (number) - The count of genuinely mismatched pixels. ### Request Example ```javascript import fs from 'fs'; import { PNG } from 'pngjs'; import pixelmatch from 'pixelmatch'; // Load two PNG images of equal dimensions const img1 = PNG.sync.read(fs.readFileSync('screenshot-baseline.png')); const img2 = PNG.sync.read(fs.readFileSync('screenshot-current.png')); const { width, height } = img1; if (img2.width !== width || img2.height !== height) { throw new Error(`Dimension mismatch: ${width}x${height} vs ${img2.width}x${img2.height}`); } // Create an output PNG to hold the visual diff const diff = new PNG({ width, height }); const numDiffPixels = pixelmatch( img1.data, img2.data, diff.data, width, height, { threshold: 0.1, includeAA: false, alpha: 0.1, aaColor: [255, 255, 0], diffColor: [255, 0, 0], diffColorAlt: null, diffMask: false, checkerboard: true, } ); fs.writeFileSync('diff.png', PNG.sync.write(diff)); const errorPercent = (100 * numDiffPixels / (width * height)).toFixed(2); console.log(`Different pixels: ${numDiffPixels}`); console.log(`Error: ${errorPercent}%`); process.exit(numDiffPixels ? 1 : 0); ``` ### Response Example (The function returns a number representing the count of differing pixels. The `output` buffer is modified in place if provided.) ``` -------------------------------- ### Include pixelmatch in Browser from CDN Source: https://github.com/mapbox/pixelmatch/blob/main/README.md Includes the pixelmatch library in a browser environment using an ES module import from a CDN. ```html