Compare Two Images in React and Highlight Differing Pixels
To show the differences between two images in color, read the pixel values of both images with a canvas, then compare the R, G, and B values of each pixel one by one. Paint pixels whose difference exceeds a chosen value (the threshold) in pink, and draw all other pixels from the original image as a faint gray. The result shows at a glance where the image changed.
Here I wrote diffImageData, which compares two images and builds the result image; loadImageData, which reads pixel values from a selected file; and App, which lets you pick two images and move the threshold. Raising the threshold hides small color changes. Also, when comparing against an image saved as JPEG, pixels in unchanged areas are counted as different. I explain both using pixel counts I actually measured.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I ran Chromium with Playwright, selected two images, and compared the displayed result pixel by pixel with an image computed by the same logic in Python (Pillow 10.2.0). The images were not photos; they were opaque 600×400 images drawn with Pillow. I did not test Firefox, Safari, mobile browsers, images with transparent areas, or processing speed on large photo-sized images.
For the test I used the two images below. The changed image differs from the original in four places. I changed the price from "1,280 yen" to "1,480 yen", moved the circle 6px to the right, and added a 3×3px black dot at the bottom right. The blue square's color changed from (0, 200, 232) to (0, 200, 212). The blue value differs by only 20, so the difference is hard to see side by side.

- 1. Reading pixel values from a selected file
- 2. Comparing pixel by pixel and painting differences pink
- 3. A component that shows the threshold and the count of differing pixels
- 4. Checking the result against the same calculation in Python
- 5. Raising the threshold hides small color changes
- 6. Comparing against JPEG makes unchanged areas count as different
Reading pixel values from a selected file
To read pixel values from an image file, draw the image loaded with createImageBitmap() onto a canvas, then extract the pixels with getImageData(). This canvas is never shown on the page; it is used only to read the values.
// Load the selected file and extract the pixel values
export async function loadImageData(file: File): Promise<ImageData> {
const bitmap = await createImageBitmap(file);
const canvas = document.createElement('canvas');
canvas.width = bitmap.width;
canvas.height = bitmap.height;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('canvas が使えません');
ctx.drawImage(bitmap, 0, 0);
bitmap.close();
return ctx.getImageData(0, 0, canvas.width, canvas.height);
}
The data of the returned ImageData holds four values per pixel (R, G, B, A), stored row by row starting from the top-left pixel. After the reading is done, the ImageBitmap is released with close().
Comparing pixel by pixel and painting differences pink
The comparison steps through the two data arrays four values at a time. For each pixel it takes the largest of the R, G, and B differences as that pixel's difference. If the difference exceeds the threshold, the pixel is pink; otherwise it is a light gray based on the original image's brightness. The result is written to an ImageData of the same size, created with new ImageData().
export type DiffResult = { image: ImageData; changed: number };
// Color used to paint the differing pixels (R, G, B)
const MARK = [216, 88, 120];
// Compare the two images pixel by pixel. Pixels where the largest R, G, or B difference exceeds the threshold are painted pink,
// All other pixels are set to a light gray based on the brightness of the image before the change
export function diffImageData(before: ImageData, after: ImageData, threshold: number): DiffResult {
if (before.width !== after.width || before.height !== after.height) {
throw new Error('2枚の画像の大きさが違います');
}
const a = before.data;
const b = after.data;
const image = new ImageData(before.width, before.height);
const out = image.data;
let changed = 0;
for (let i = 0; i < a.length; i += 4) {
const d = Math.max(Math.abs(a[i] - b[i]), Math.abs(a[i + 1] - b[i + 1]), Math.abs(a[i + 2] - b[i + 2]));
if (d > threshold) {
out[i] = MARK[0];
out[i + 1] = MARK[1];
out[i + 2] = MARK[2];
changed++;
} else {
// Compute the brightness (0 to 255) and move it toward white so it looks faded
const lum = 0.299 * a[i] + 0.587 * a[i + 1] + 0.114 * a[i + 2];
const v = Math.round(255 - (255 - lum) * 0.25);
out[i] = out[i + 1] = out[i + 2] = v;
}
out[i + 3] = 255;
}
return { image, changed };
}
Unchanged areas are kept as a light gray rather than pure white so you can still see where the pink pixels are. The gray level is set by bringing the brightness computed from R, G, and B closer to white. If the two images have different sizes, pixels at the same position cannot be compared, so the function throws an error without comparing.
A component that shows the threshold and the count of differing pixels
App keeps the two ImageData values and the threshold in state, and computes the comparison with useMemo. As long as the images and threshold do not change, it does not compare all pixels again on each re-render. The result image is drawn to the canvas with putImageData() inside a useEffect.
import { useEffect, useMemo, useRef, useState } from 'react';
import type { ChangeEvent } from 'react';
import { diffImageData, loadImageData } from './diff';
export function App() {
const [before, setBefore] = useState<ImageData | null>(null);
const [after, setAfter] = useState<ImageData | null>(null);
const [threshold, setThreshold] = useState(0);
const canvasRef = useRef<HTMLCanvasElement>(null);
// Only compare when both images are present and have the same size
const sameSize = before && after && before.width === after.width && before.height === after.height;
const result = useMemo(
() => (before && after && sameSize ? diffImageData(before, after, threshold) : null),
[before, after, sameSize, threshold],
);
// Draw the comparison result on the canvas
useEffect(() => {
const canvas = canvasRef.current;
if (!result || !canvas) return;
canvas.width = result.image.width;
canvas.height = result.image.height;
canvas.getContext('2d')?.putImageData(result.image, 0, 0);
}, [result]);
function pick(set: (d: ImageData) => void) {
return async (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) set(await loadImageData(file));
};
}
const total = result ? result.image.width * result.image.height : 0;
return (
<main>
<label className="pick">
変更前の画像
<input type="file" accept="image/*" onChange={pick(setBefore)} />
</label>
<label className="pick">
変更後の画像
<input type="file" accept="image/*" onChange={pick(setAfter)} />
</label>
<label className="threshold">
しきい値:{threshold}
<input type="range" min={0} max={64} step={8} value={threshold} onChange={(e) => setThreshold(Number(e.target.value))} />
</label>
{before && after && !sameSize && (
<p className="error" role="alert">
画像の大きさが違います({before.width}×{before.height} と {after.width}×{after.height})
</p>
)}
{result && (
<>
<p className="info">
違う画素:{result.changed.toLocaleString()} 個(全体の {((result.changed / total) * 100).toFixed(2)}%)
</p>
<canvas ref={canvasRef} className="result" role="img" aria-label="違う部分をピンクで示した画像" />
</>
)}
</main>
);
}
When the sizes differ, the app does not compare and instead shows both sizes, such as "Image sizes differ (600×400 and 601×401)". In the test, choosing a 600×400 image and a 601×401 image showed this message, and the result canvas and the count of differing pixels were not displayed.
The CSS is as follows. The result canvas is fitted to the screen width with max-width: 100%. On a 420px-wide screen, the 600×400 result was displayed shrunk to 389.98×260.66px.
body { margin: 0; font-family: "Noto Sans CJK JP", sans-serif; color: #1f2a30; background: #fff; }
main { padding: 16px; max-width: 620px; }
.pick, .threshold { display: flex; align-items: center; gap: 8px; margin: 0 0 10px; font-size: 14px; }
.info { font-size: 14px; margin: 0 0 8px; }
.error { color: #d85878; font-size: 14px; }
.result { display: block; max-width: 100%; height: auto; border: 1px solid #9aa5ab; }
The following GIF shows what happens after selecting the before and after images and raising the threshold from 0 to 16, then from 16 to 24. The slider moves in steps of 8, so the first change passes through 8. At thresholds 0 and 16 the whole square is pink, but at 24 the square is no longer pink, and the count of differing pixels drops from 42,831 to 2,417.

For the circle, only the thin left and right parts that do not overlap before and after the move turned pink. Because the fill color is the same, pixels in the overlapping part did not change.
Checking the result against the same calculation in Python
I selected the two images with Playwright and saved the result canvas as a PNG for each threshold. The output below compares each saved PNG pixel by pixel with an image computed by the same logic in Python. It also counts the pink pixels, split into the four changed areas and everything else.
after-png-t0.png: 600x400 正解と違う画素 0 / 240000, 不透明 True | ピンクの画素 値段の文字 372, 丸 2088, 黒い点 9, 四角の色 40401, それ以外 0
after-png-t16.png: 600x400 正解と違う画素 0 / 240000, 不透明 True | ピンクの画素 値段の文字 333, 丸 2088, 黒い点 9, 四角の色 40401, それ以外 0
after-png-t24.png: 600x400 正解と違う画素 0 / 240000, 不透明 True | ピンクの画素 値段の文字 320, 丸 2088, 黒い点 9, 四角の色 0, それ以外 0
after-png-t64.png: 600x400 正解と違う画素 0 / 240000, 不透明 True | ピンクの画素 値段の文字 289, 丸 2088, 黒い点 9, 四角の色 0, それ以外 0
At every threshold, the number of pixels differing from the Python result was 0. The pink pixels were only inside the four changed areas, and there were none anywhere else. When I compared identical images, the number of differing pixels was 0.
before-png-t0.png: 600x400 正解と違う画素 0 / 240000, 不透明 True | ピンクの画素 値段の文字 0, 丸 0, 黒い点 0, 四角の色 0, それ以外 0
Raising the threshold hides small color changes
I measured the differences in the four changed areas between the before and after images. The difference is the largest of the R, G, and B differences for each pixel.
値段の文字: 違う画素 372、差の最小 1、最大 249
丸: 違う画素 2088、差の最小 173、最大 224
黒い点: 違う画素 9、差の最小 253、最大 253
四角の色: 違う画素 40401、差の最小 20、最大 20
Every pixel in the square has a difference of 20. So up to a threshold of 16, all 40,401 pixels of the square are pink, and at 24 none of them are. The threshold means "treat as different only if the difference exceeds this value", so a color change whose difference is at or below the threshold does not appear in the result.
The price digits had differences ranging from 1 up to 249. When I raised the threshold to 0, 16, 24, and 64, the pink pixel counts fell to 372, 333, 320, and 289. As the GIF shows, the shapes of "2" and "4" are still pink at a threshold of 24. The circle and the black dot have differences of 173 or more, so every pixel stayed pink even at a threshold of 64.
If you compare images like PNGs, where the values of unchanged pixels are exactly the same, set the threshold to 0 and no small color change will be missed.
Comparing against JPEG makes unchanged areas count as different
I saved the after image as a JPEG (quality 85) and compared it with the before PNG. At a threshold of 0, 94.98% of all pixels were pink. Even the unchanged background is almost entirely pink. JPEG is a lossy compression format that discards part of the image data to reduce file size. Comparing the after PNG with the JPEG saved from it, 227,956 of the 240,000 pixels had different values, with a maximum difference of 92.
after.png と after.jpg: 違う画素 227956 、差の最大 92 、差が 64 を超える画素 33
As the threshold rises, the pink in unchanged areas decreases, but the color change in the square disappears at the same time.
after-jpg-t0.png: 600x400 正解と違う画素 0 / 240000, 不透明 True | ピンクの画素 値段の文字 10562, 丸 16375, 黒い点 9, 四角の色 40401, それ以外 160616
after-jpg-t8.png: 600x400 正解と違う画素 0 / 240000, 不透明 True | ピンクの画素 値段の文字 3068, 丸 3223, 黒い点 9, 四角の色 40399, それ以外 9233
after-jpg-t16.png: 600x400 正解と違う画素 0 / 240000, 不透明 True | ピンクの画素 値段の文字 1936, 丸 2477, 黒い点 9, 四角の色 40286, それ以外 5815
after-jpg-t24.png: 600x400 正解と違う画素 0 / 240000, 不透明 True | ピンクの画素 値段の文字 1051, 丸 2335, 黒い点 9, 四角の色 1200, それ以外 3187
after-jpg-t32.png: 600x400 正解と違う画素 0 / 240000, 不透明 True | ピンクの画素 値段の文字 543, 丸 2268, 黒い点 9, 四角の色 804, それ以外 1386
after-jpg-t48.png: 600x400 正解と違う画素 0 / 240000, 不透明 True | ピンクの画素 値段の文字 325, 丸 2154, 黒い点 9, 四角の色 16, それ以外 399
after-jpg-t64.png: 600x400 正解と違う画素 0 / 240000, 不透明 True | ピンクの画素 値段の文字 292, 丸 2100, 黒い点 9, 四角の色 4, それ以外 1

At a threshold of 32, pink in unchanged areas dropped to 1,386 pixels, but in the square only 804 pixels of the outline were pink, so the color change of the whole square was no longer visible. At 64, unchanged areas had just 1 pink pixel, but the square had only 4 pink pixels. With this combination, no threshold removed only the changes caused by JPEG while keeping the color change of the square.
If you want to catch even small color changes, save both images in a lossless format such as PNG and compare them at a threshold of 0. If you have no choice but to compare against JPEG, choose the threshold knowing that any color change at or below that value will not appear in the result.





