Pixelmatch 技术文档
Pixelmatch 是一款轻量级、高性能的 JavaScript 图像像素对比库,专为测试环境中的截图比较设计。它具备精准的抗锯齿像素检测以及感知色彩差异度量的能力,灵感源自 Resemble.js 和 Blink-diff,但体积更小巧(约150行代码),无依赖,并且能够处理原始图像数据数组,适用于任何运行环境(Node.js 或浏览器)。
安装指南
Node.js环境
通过NPM安装Pixelmatch非常简单,打开终端并输入以下命令:
npm install pixelmatch
浏览器环境
对于Web项目,您可以直接通过CDN引入模块:
<script type="module">
import pixelmatch from 'https://cdn.jsdelivr.net/npm/pixelmatch@latest/dist/pixelmatch.mjs';
</script>
或者使用ESM方式进行导入:
<script type="module">
import pixelmatch from 'https://esm.run/pixelmatch';
</script>
项目的使用说明
Pixelmatch的核心功能在于比较两个图像之间的像素差异。以下是在不同环境下的基本用法:
Node.js示例
假设您已经有了两个PNG图像的数据缓冲区img1
和img2
,可以通过以下代码进行比较:
const fs = require('fs');
const { PNG } = require('pngjs');
const pixelmatch = require('pixelmatch');
// 读取图片数据
const img1 = PNG.sync.read(fs.readFileSync('path/to/img1.png'));
const img2 = PNG.sync.read(fs.readFileSync('path/to/img2.png'));
// 获取图片尺寸
const { width, height } = img1;
// 创建用于存储差异图像的新PNG对象
const diff = new PNG({ width, height });
// 执行像素匹配
const numDiffPixels = pixelmatch(img1.data, img2.data, diff.data, width, height, { threshold: 0.1 });
// 写入差异图像到文件
fs.writeFileSync('path/to/diff.png', PNG.sync.write(diff));
console.log(`存在${numDiffPixels}个不同的像素`);
浏览器环境示例
在Web环境中,您可以这样使用Pixelmatch来比较Canvas图像数据:
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>
<script>
const canvas1 = document.getElementById('canvas1');
const ctx1 = canvas1.getContext('2d');
// 假设canvas1和canvas2已经被正确填充了图像
const img1 = ctx1.getImageData(0, 0, canvas1.width, canvas1.height);
const img2 = ctx2.getImageData(0, 0, canvas2.width, canvas2.height);
const diff = ctx1.createImageData(canvas1.width, canvas1.height);
pixelmatch(img1.data, img2.data, diff.data, canvas1.width, canvas1.height, { threshold: 0.1 });
// 显示差异图
ctx1.putImageData(diff, 0, 0);
</script>
项目API使用文档
主要函数是pixelmatch()
,其定义如下:
pixelmatch(img1, img2, output, width, height, [options]);
img1
,img2
: 需要比较的两幅图像的数据(Buffer
,Uint8Array
或Uint8ClampedArray
类型)。图像尺寸必须相同。output
: 差异图的图像数据,若不需要,则传null
。width
,height
: 图像宽度和高度。options
(可选):threshold
: 匹配阈值,范围从0到1,较小值表示更高的敏感度,默认为0.1。- 其他如
includeAA
,alpha
,aaColor
,diffColor
,diffColorAlt
,diffMask
等参数控制差异图的生成细节。
项目安装方式已包含在“安装指南”部分,遵循上述指导即可将Pixelmatch集成至您的项目中,享受高效、简洁的图像比较体验。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考