Skip to content Skip to sidebar Skip to footer

Getimagedata Always Returning 0

I have been trying to make a script that compares two images in HTML5 and Javascript. But for some odd reason, it always returns that the images are completely the same. And when l

Solution 1:

You are not waiting until your images have loaded and drawn before performing your comparison. Try this:

var img = newImage;
img.onload = function(){
  ctx1.drawImage(img,0,0);
  var img = newImage;
  img.onload = function(){
    ctx2.drawImage(img,0,0);
    // diff them here
  };
  img.src = 'cat.jpg';
};
img.src = 'cat.jpg';

As shown above, you should always set your srcafter your onload.

Solution 2:

I suspect that the problem is that your image data is probably not ready at the point you try to use it for the canvas. If you defer that code to the onload handlers, that will (probably) help:

var img1 = newImage(), count = 2;
img1.src = "cat.jpg";
img1.onload = function() {
    ctx1.drawImage(img1, 0, 0);
    checkReadiness();
}
var img2 = newImage();
img2.src = "bird.jpg";
img2.onload = function() {
    ctx2.drawImage(img2, 0, 0);
    checkReadiness();
}

functioncheckReadiness() {
  if (--count !== 0) return;

  for(var x = 0; x<c1.width; x++) {  // For each x valuefor(var y = 0; y<c1.height; y++) { // For each y valuevar data1 = ctx1.getImageData(x, y, 1, 1);
        var data2 = ctx2.getImageData(x, y, 1, 1);
        if (data1.data[0] == data2.data[0] && data1.data[1] == data2.data[1] && data1.data[2] == data2.data[2]) {
            match++;
        }
    }
  }
  var pixels = c1.width*c1.height;
  match = match/pixels*100;
  document.getElementById("match").innerHTML = match + "%";
}

All I did was add a function wrapper around your code. That function checks the image count variable I added, and only when it's zero (i.e., only after both images have loaded) will it do the work.

(This may be superstition, but I always assign the "onload" handler before I set the "src" attribute. I have this idea that, perhaps only in the past, browsers might fail to run the handler if the image is already in the cache.)

Now another thing: you probably should just get the image data once, and then iterate over the returned data. Calling "getImageData()" for every single pixel is going to be a lot of work for the browser to do.

Post a Comment for "Getimagedata Always Returning 0"