1

I have two different URL's,i want to check whether images with these URL is same or different in java script.I am checking for exact image. For e.g. these two are URL's

Images Path

url1="https://usercontent.googleapis.com/freebase/v1/image/m/030z4z"
url2="https://usercontent.googleapis.com/freebase/v1/image/m/09jjsg"

2 Answers2

6

You can convert images to base64 string and then compare strings.

Try something like this:

/**
 * Convert an image 
 * to a base64 string
 * @param  {String}   url         
 * @param  {Function} callback    
 * @param  {String}   [outputFormat=image/png]           
 */
function convertImgToBase64(url, callback, outputFormat){
    var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'),
        img = new Image;
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var dataURL;
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback.call(this, dataURL);
        canvas = null; 
    };
    img.src = url;
}

var img1 = "http://image_url_1",
    img2 = "http://image_url_2"

convertImgToBase64(img1, function(base64Img1){
    convertImgToBase64(img2, function(base64Img2){
        alert(base64Img1 == base64Img2);
    });
});
Gleb
  • 1,312
  • 3
  • 18
  • 36
1

First, compare image sizes using

var img=document.getElementById("myImage"); //Which is an image element on DOM

img.naturalWidth and img.naturalHeight for both images.

If the image sizes are exactly the same add two canvases to the DOM the same size as the image and draw the respective images using;

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

ctx.drawImage(img,0,0);

Then compare pixel by pixel using a similar method to this

Community
  • 1
  • 1
Ali Naci Erdem
  • 435
  • 2
  • 12