getImageData()数组返回角度5的全0

时间:2018-12-02 14:48:36

标签: javascript angular ecmascript-6 getimagedata

在画布内部渲染图像后,我试图获取图像的rgb值。但是我得到全0的回报。我在渲染图像后不确定是否为什么要得到0来尝试使用getImageData()。

我的代码:

fileSelected: File;
preview: any;
context: CanvasRenderingContext2D;
hue: any;
myImageData:any

onFileSelect(e: any) {
    let canvas = this.mycanvas.nativeElement;
    let context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height)
    let imgData;
    this.fileSelected = e.target.files[0];
    let reader = new FileReader()
    reader.onload = (e: any) => {
        var image = new Image();
        image.onload = function () {
            image.width = canvas.width;
            image.height = canvas.height;
            context.drawImage(image, 0, 0, canvas.width, canvas.height)
         };
        image.src = e.target.result

    }
    reader.readAsDataURL(this.fileSelected);
    this.myImageData = context.getImageData(0, 0, 100, 100);

    this.hue = this.calculateHue(this.fileSelected, this.myImageData);
}

calculateHue(file, myImageData) {

     console.log("rgb====", myImageData.data)
    return null
}

我已经通过这些链接getImageData() returning all zerosgetImageData() returning all 0'sgetImageData always returning 0

但是没有一个答案能解决它。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

加载图像后,您将立即写入画布,但是一旦选择了文件,便尝试从画布中读取内容,

this.myImageData = context.getImageData(0, 0, 100, 100);
this.hue = this.calculateHue(this.fileSelected, this.myImageData);

进入image.onload并在context.drawImage(image, 0, 0, canvas.width, canvas.height)调用之后,因此确保有可以读取的图像数据。

它应该看起来像这样:

onFileSelect(e: any) {
    let canvas = this.mycanvas.nativeElement;
    let context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height)
    let imgData;
    this.fileSelected = e.target.files[0];
    let reader = new FileReader();
    let self = this;

    reader.onload = (e: any) => {
        var image = new Image();
        image.onload = () => {
            image.width = canvas.width;
            image.height = canvas.height;
            context.drawImage(image, 0, 0, canvas.width, canvas.height)
            // Move it here
            self.myImageData = context.getImageData(0, 0, 100, 100);
            self.hue = this.calculateHue(self.fileSelected, self.myImageData);
         };

        image.src = e.target.result
    }
    reader.readAsDataURL(this.fileSelected);
}