2015-09-06 67 views
0

我有下面的代碼這樣做:在圖像上使用「getImageData(...)」(或類似)的方法?

img = new Image(); 
img.src = document.getElementById("input").value; 
img.onload = function(){ 
    console.log("loaded"); 
    c.height = img.height; 
    c.width = img.width; 
    dimensions =[img.width,img.height]; 
    ctx.drawImage(img,0,0,img.width,img.height); 
    imageData = ctx.getImageData(0,0,img.width,img.height).data; 
    ctx.clearRect(0,0,c.width,c.height); 
}; 

然而,谷歌瀏覽器,它拋出的錯誤Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

不僅如此,它是做一個簡單的動作非常複雜的方式。任何更好的方法來做到這一點?如果沒有,幫助錯誤?

回答

1

你想用數據做什麼?取決於你可能使用FileReader.readAsDataURL(),特別是因爲你正在嘗試獲取整個圖像的數據。

一些代碼:

var input = document.getElementById('file'); 
    var ctx2 = document.getElementById('uploadcanvas').getContext('2d'); 
    var img2 = new Image; 
    var canvas = document.getElementById('uploadcanvas'); 
    var imgprop = document.createElement("img"); 
    var reader = new FileReader(); 
    ctx2.save(); 
    reader.onloadend = function(e){ 
     imgprop.src = e.target.result 
     imgprop.onload = function(){ 
      ctx2.restore(); 
      URL.revokeObjectURL(img2.src); 
      ctx2.clearRect(0, 0, 100,100); 
      var width = imgprop.width; 
      var height = imgprop.height; 
      console.log(width, height); 
      canvas.width = width; 
      canvas.height = height; 
      img2.src = URL.createObjectURL(input.files[0]); 
      img2.onload = function() { 
       $('#display-image').css('display', "inline"); 
       ctx2.drawImage(img2, 0, 0); 
      //URL.revokeObjectURL(img2.src); 
      }; 
      $("#button").removeAttr("disabled"); 
      $("#button").html("Upload to Facebook"); 
     } 

    }; 
    reader.readAsDataURL(input.files[0]); 



function dataURItoBlob(dataURI) { 
     var byteString = atob(dataURI.split(',')[1]); 
     var ab = new ArrayBuffer(byteString.length); 
     var ia = new Uint8Array(ab); 
     for (var i = 0; i < byteString.length; i++) { 
       ia[i] = byteString.charCodeAt(i); 
     } 
     return new Blob([ab], { 
       type: 'image/png' 
     }); 
} 
+0

我想知道每一個像素精確的色彩。正如我想要一個RGB或每個像素的十六進制,如ctx.getImageData()所做的那樣。 – Fuzzyzilla

+0

那麼在這種情況下,它絕對看起來你最好是修復安全警告,而不是在這裏發明輪子。爲了解決安全問題,請嘗試加載圖像,使用filreader獲取二進制數據/ blob,將其放入新圖像並根據此圖像製作畫布。我懷疑瀏覽器將無法確定它來自哪裏。 – 2015-09-06 00:49:42

+0

謝謝。我從來沒有見過這樣的代碼。你能鏈接或爲學習目的解釋嗎? – Fuzzyzilla

相關問題