I am using the Canvas NPM library to perform a delta comparison between two images. Both images have the same dimensions (equal width and height). The Method takes two images as base64 string and I am comparing every pixel of the two images.
In Chrome and Edge the loop takes about 20–50ms to execute, whereas in Firefox it takes approximately 700–800ms. Could this be due to Firefox having slower memory management compared to Chrome and Edge?
async function createDeltaImageFromBase64(currentImageBase64, previousImageBase64) {
if(currentImageBase64 == null || previousImageBase64 ==null){
return previousImageBase64;
}
// Load images using base64 data URIs
const currentImage = await loadImage(currentImageBase64);
const previousImage = await loadImage(previousImageBase64);
// Ensure the dimensions match
const width = Math.min(currentImage.width, previousImage.width);
const height = Math.min(currentImage.height, previousImage.height);
// Create a canvas for the delta image
const canvas = createCanvas(width, height);
const ctx = canvas.getContext('2d');
// Draw the current image on the canvas
ctx.drawImage(currentImage, 0, 0, width, height);
const currentImageData = ctx.getImageData(0, 0, width, height);
// Draw the previous image on a temporary canvas
const tempCanvas = createCanvas(width, height);
const tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(previousImage, 0, 0, width, height);
const previousImageData = tempCtx.getImageData(0, 0, width, height);
// Create the delta image
const deltaImageData = ctx.createImageData(width, height);
const { data: currentData } = currentImageData;
const { data: previousData } = previousImageData;
const { data: deltaData } = deltaImageData;
for (let i = 0; i < currentData.length; i += 4) {
// Compare RGBA channels
const isDifferent =
currentData[i] !== previousData[i] ||
currentData[i + 1] !== previousData[i + 1] ||
currentData[i + 2] !== previousData[i + 2] ||
currentData[i + 3] !== previousData[i + 3];
if (isDifferent) {
// Copy current image pixel
deltaData[i] = currentData[i]; // Red
deltaData[i + 1] = currentData[i + 1]; // Green
deltaData[i + 2] = currentData[i + 2]; // Blue
deltaData[i + 3] = currentData[i + 3]; // Alpha
} else {
// Set to transparent
deltaData[i] = 0;
deltaData[i + 1] = 0;
deltaData[i + 2] = 0;
deltaData[i + 3] = 0;
}
}
// Put the delta image data back on the canvas
ctx.putImageData(deltaImageData, 0, 0);
// Return the delta image as a base64 string
return canvas.toDataURL(); // Returns a base64 data URI
}