Pixelmatch 技术文档

Pixelmatch 技术文档

pixelmatch The smallest, simplest and fastest JavaScript pixel-level image comparison library pixelmatch 项目地址: https://gitcode.com/gh_mirrors/pi/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图像的数据缓冲区img1img2,可以通过以下代码进行比较:

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: 需要比较的两幅图像的数据(BufferUint8ArrayUint8ClampedArray类型)。图像尺寸必须相同。
  • output: 差异图的图像数据,若不需要,则传null
  • width, height: 图像宽度和高度。
  • options(可选):
    • threshold: 匹配阈值,范围从0到1,较小值表示更高的敏感度,默认为0.1。
    • 其他如includeAA, alpha, aaColor, diffColor, diffColorAlt, diffMask等参数控制差异图的生成细节。

项目安装方式已包含在“安装指南”部分,遵循上述指导即可将Pixelmatch集成至您的项目中,享受高效、简洁的图像比较体验。

pixelmatch The smallest, simplest and fastest JavaScript pixel-level image comparison library pixelmatch 项目地址: https://gitcode.com/gh_mirrors/pi/pixelmatch

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

任婉迅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值