在图像上使用" getImageData(...)"(或类似)的方法?

时间:2015-09-06 00:34:47

标签: javascript image canvas

我有以下代码:

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 个答案:

答案 0 :(得分: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'
        });
}