MCPcopy Create free account
hub / github.com/Snapchat/Valdi / pixelDiff

Function pixelDiff

apps/snapshot_tests/src/PixelDiff.ts:10–59  ·  view source on GitHub ↗
(baseline: IBitmap, actual: IBitmap, tolerance: number)

Source from the content-addressed store, hash-verified

8}
9
10export function pixelDiff(baseline: IBitmap, actual: IBitmap, tolerance: number): PixelDiffResult {
11 const baselineInfo = baseline.getInfo();
12 const actualInfo = actual.getInfo();
13
14 if (baselineInfo.width !== actualInfo.width || baselineInfo.height !== actualInfo.height) {
15 return {
16 totalPixels: baselineInfo.width * baselineInfo.height,
17 mismatchedPixels: baselineInfo.width * baselineInfo.height,
18 mismatchPercent: 100,
19 maxDifference: 255,
20 };
21 }
22
23 const { width, height, rowBytes } = baselineInfo;
24 const actualRowBytes = actualInfo.rowBytes;
25 const bytesPerPixel = 4;
26 const totalPixels = width * height;
27 let mismatchedPixels = 0;
28 let maxDifference = 0;
29
30 baseline.accessPixels(baselineView => {
31 actual.accessPixels(actualView => {
32 for (let y = 0; y < height; y++) {
33 for (let x = 0; x < width; x++) {
34 const baseOffset = y * rowBytes + x * bytesPerPixel;
35 const actOffset = y * actualRowBytes + x * bytesPerPixel;
36 const rDiff = Math.abs(baselineView.getUint8(baseOffset) - actualView.getUint8(actOffset));
37 const gDiff = Math.abs(baselineView.getUint8(baseOffset + 1) - actualView.getUint8(actOffset + 1));
38 const bDiff = Math.abs(baselineView.getUint8(baseOffset + 2) - actualView.getUint8(actOffset + 2));
39 const aDiff = Math.abs(baselineView.getUint8(baseOffset + 3) - actualView.getUint8(actOffset + 3));
40
41 const pixelMax = Math.max(rDiff, gDiff, bDiff, aDiff);
42 if (pixelMax > tolerance) {
43 mismatchedPixels++;
44 }
45 if (pixelMax > maxDifference) {
46 maxDifference = pixelMax;
47 }
48 }
49 }
50 });
51 });
52
53 return {
54 totalPixels,
55 mismatchedPixels,
56 mismatchPercent: totalPixels > 0 ? (mismatchedPixels / totalPixels) * 100 : 0,
57 maxDifference,
58 };
59}

Callers 1

compareSnapshotsFunction · 0.90

Calls 2

getInfoMethod · 0.65
accessPixelsMethod · 0.65

Tested by

no test coverage detected