Reputation: 356
I have the following code to do so:
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);
};
However, on google chrome it throws the error Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
Not only that, it's a very complex way of doing a simple action. Any better ways of doing this? If not, help with the error?
Upvotes: 0
Views: 170
Reputation:
What are you trying to do with the data? Depending on that you could possible use the FileReader.readAsDataURL(), especially since you are trying to get the data for the whole image.
Some code:
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'
});
}
Upvotes: 1