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

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

问题描述

我正在尝试确定两个图像在 JavaScript 中是否相同(即使源 URL 不同).

I am trying to determine if two images are the same in JavaScript (even if the source URLs are different).

我的具体用例在 Chrome 扩展程序中(尽管这是一个 chrome 扩展程序并没有真正考虑到问题).我可以通过将 img src 设置为:'chrome://favicon/'+url 其中,'url' 是网站的实际 URL.但是,我现在想找到所有独特的网站图标.鉴于它们都有不同的内部数据库 URL,有没有一种简单的方法来比较 JavaScript 中的图像?

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?

推荐答案

不,没有特别简单的方法可以做到这一点.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.

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

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.

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

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天全站免登陆