如何在JavaScript中匹配两个图像?

时间:2015-03-11 05:33:46

标签: javascript html image cordova

我希望将两个图像相互匹配,如果匹配则结果为true。如果不是,那么它将返回false。但我希望它能用JavaScript。

1 个答案:

答案 0 :(得分:1)

您可以通过将图片转换为base64字符串来检查

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 a = new Image(),
    b = new Image();
a.src = url_a;
b.src = url_b;

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
}

您可以看到this link了解更多信息。