在JavaScript中比较两个图片 [英] Compare two Images in JavaScript

查看:942
本文介绍了在JavaScript中比较两个图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图确定两个图像在JavaScript中是否相同(即使src网址不同)。



我的具体用例是在chrome扩展内(虽然这是一个chrome扩展不真正考虑到这个问题)。我可以通过设置img src为:
'chrome:// favicon /'+ url 来获取存储在chrome内部数据库中的favicon png的行为url是网站的实际网址。然而,我现在想找到所有独特的favicons。



感谢

div class =h2_lin>解决方案

不,没有特别的 easy 方法来做到这一点。 JavaScript不是用于处理低级操作,例如直接处理二进制数据,例如图像处理。



您可以使用< canvas> 元素对每个图片进行base64编码,以及然后比较生成的 base64 字符串,但这只会告诉您图片是否相同。



要使用 getBase64Image 函数(在我链接的答案中定义)来比较两个图像:

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

//可能需要等待a和b实际加载,忽略这个
var a_base64 = getBase64Image(a),
b_base64 = getBase64Image(b);

if(a_base64 === b_base64)
{
//它们是相同的
}
else
{
/ /你可能猜到这是什么意思
}


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?

Thanks

解决方案

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
}

这篇关于在JavaScript中比较两个图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆