Compare two Images in JavaScript

Spread the love

Question Description

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:
'chrome://favicon/'+url 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?


Practice As Follows

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 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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.