我正在Tampermonkey(在Google Chrome中)中使用javascript,如果两个图像相同/非常相似,我想比较两个图像。
我以为我可以通过使用canvas元素并比较生成的字符串来做到这一点,但是无论我选择什么图像,我总会得到它们是相同的...:/
所以比较似乎不起作用,我也不知道为什么吗?
编辑1:添加了一个计时器,以等待图像加载 /
/ ==UserScript==
// @name ImageCompare
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match *://*/*
// @match www*
// @grant none
// ==/UserScript==
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
var x = new Image();
var y = new Image();
var url_x = "https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2010/03/google_logo.jpg";
var url_y = "https://nairobigarage.com/2017/wp-content/uploads/2015/02/6_logo_predesign.jpg";
x.src = 'chrome://favicon/' + url_x;
y.src = 'chrome://favicon/' + url_y;
var x_base64 = getBase64Image(x);
var y_base64 = getBase64Image(y);
sleep(5000).then(() => {
if (x_base64 === y_base64)
{
alert("identical");
}
else
{
alert("not identical");
}
});
答案 0 :(得分:4)
您需要等待图像加载,可以使用console.log在图像加载后通知您
var img = new Image();
img.onload = ()=>{
//do work
};
所以:
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
var x = new Image();
var y = new Image();
var url_x = "https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2010/03/google_logo.jpg";
var url_y = "https://nairobigarage.com/2017/wp-content/uploads/2015/02/6_logo_predesign.jpg";
x.src = 'chrome://favicon/' + url_x;
y.src = 'chrome://favicon/' + url_y;
//make the load events into promises
var xPromise = new Promise((resolve)=>{
x.onload = resolve;
});
var yPromise = new Promise((resolve)=>{
y.onload = resolve;
});
Promise.all([xPromise,yPromise]).then(()=>{
var x_base64 = getBase64Image(x);
var y_base64 = getBase64Image(y);
if(x_base64 == y_base64){
//match
} else {
//no match
}
});
请注意,尽管您尝试从chrome://
协议加载资源,但是由于安全限制,您实际上无法获取跨源资源的数据。从页面运行所在的域中加载资源,或者使用文件输入来获取图像。