JMH JMH - 7 months ago 40
Javascript Question

Compare two Images in JavaScript

I am trying to determine if two images are the same in javascript (even if the src urls are different).

My specific use case is within a chrome extension (though this being a chrome extension doesn't really factor into the question). I can get the imgage of a favicon png stored within chrome's internal database by setting the img src to:

where the url is the actual url of the website. However, I now want to find all the unique favicons. Given that they all will have a different URL to the internal database, is there an easy way to compare images in javascript?



No, there is no especially easy way to do this. JavaScript was not made for handling low-level operations such as working directly with binary data for, say, image processing.

You could use a <canvas> element to base64 encode each image, and then compare the resulting base64 strings, but this will only tell you whether or not the images are identical.

To use the getBase64Image function (defined in the answer I linked) to compare two images:

var a = new Image(),
    b = new Image();
a.src = 'chrome://favicon/' + url_a;
b.src = 'chrome://favicon/' + url_b;

// might need to wait until a and b have actually loaded, ignoring this for now
var a_base64 = getBase64Image(a),
    b_base64 = getBase64Image(b);

if (a_base64 === b_base64)
    // they are identical
    // you can probably guess what this means