2017-04-26 46 views
0

我試圖循環瀏覽網頁上顯示的圖像,以確定其中哪些圖像具有最左邊的像素白色。從網頁中識別具有白色背景的圖像

 $('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>

我錯過了什麼嗎?我從來沒有嘗試過使用此方法。如果你知道不同的版本,請告訴我。

+0

1)你確定所有的外部圖像是正確的CORS頭被髮送? 2)'getImageData()。data'總是返回一個數組(r,g,b,a值)。所以你正在給'data-pixel'屬性分配一個數組。你確定嗎? – devnull69

+0

是的,你錯過了一些東西:正如devnull69正確說明,如果你的圖像沒有提供正確的CORS頭,圖像將不會加載。但是如果你解決了#1問題,你可能會注意到它:即使從dataURI中加載一個圖像是異步的,即使它被緩存,它也總是異步的。所以當你調用'drawImage'的時候,圖像還沒有加載,畫布上也沒有畫出任何東西('0,0,0,0'是一個透明的像素,而不是白色的[255,255,255 ,255]')。當然,只有在圖像加載後才需要調用其他所有內容。 – Kaiido

+0

圖像在我運行的時候加載。我通過控制檯加載它,我受到打擊並錯過了。有時它會給我正確的值,有時候它只是給所有人增加0,0,0,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(); 

    }; 

});