从网页识别带有白色背景的图像

时间:2017-04-26 11:08:42

标签: javascript jquery html

我正在尝试遍历网页上显示的图片,以确定其中哪一个最左边的像素为白色。

     $('img').each(function(){

        // create an image object using the current image SRC
        var image = new Image();
        image.crossOrigin = "Anonymous";
        image.src = $(this).attr('src');

        //create a canvas and place the image inside the canvas element
        var canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        canvas.getContext('2d').drawImage(image, 0, 0, image.width, image.height);

        //grab pixel data
        var pixel = canvas.getContext('2d').getImageData(0, 0, 1, 1).data;
        $(this).attr('data-pixel', pixel);

        //remove canvas
        $('canvas').remove();

    });

问题是这一直在起作用。当我在单个图像上运行它时,它大部分时间都可以工作。但是当我浏览所有图像时,我得到了data-pixel="0,0,0,0"></img>

我错过了什么吗?我之前从未尝试过使用此方法。如果您知道其他版本,请告诉我们。

1 个答案:

答案 0 :(得分:0)

基于上面的评论,我更改了代码以触发画布创建和图像绘制onload,如下所示:

    $('img').each(function() {

  var $that = $(this);
  var image = new Image();
  var canvas = document.createElement('canvas');   
  var imageSource = $that.attr('src');
  image.crossOrigin = 'Anonymous';
  image.src = imageSource;
  image.onload = function() {

      canvas.width = image.width;
      canvas.height = image.height;
      canvas.getContext('2d').drawImage(image, 0, 0, image.width, image.height);
      //grab pixel data
      var pixel = canvas.getContext('2d').getImageData(0, 0, 1, 1).data;
      $that.attr('data-pixel', pixel.toString());

      if (parseInt(pixel[0]) > 250 && parseInt(pixel[1]) > 250 && parseInt(pixel[2]) > 250) {

          $that.addClass( 'white' );
          $that.closest('table').prepend('<h5>White Background</h5>');

      }
      //remove canvas
      console.log(pixel.toString());
      $('canvas').remove();

  };

});