Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two Images in JavaScript

I am trying to determine if two images are the same in JavaScript (even if the source 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 image of a favicon png stored within Chrome's internal database by setting the img src to: 'chrome://favicon/'+url where '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?

like image 202
JMH Avatar asked May 19 '11 23:05

JMH


People also ask

How can you tell if two pictures are similar?

You can use the imagehash library to compare similar images. Since the images are not exactly the same, there will be some differences, so therefore we use a cutoff value with an acceptable maximum difference. That difference between the hash objects is the number of bits that are flipped.

What is image () in JavaScript?

Image() The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document. createElement('img') .


1 Answers

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 } else {     // you can probably guess what this means } 
like image 121
Matt Ball Avatar answered Sep 28 '22 04:09

Matt Ball