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?
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.
Image() The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document. createElement('img') .
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With