javascriptangularecmascript-6getimagedata

getImageData() array is returning all 0s in angular 5


I am trying to get the rgb value of an image after I render the image inside canvas. However I am getting all 0s in return. I am trying to use getImageData() after I render the image not sure why I am getting 0s in return.

My Code :

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
}

I have gone through these links getImageData() returning all zeros, getImageData() returning all 0's, getImageData always returning 0

But none of the answers solved it. What am I doing wrong?


Solution

  • You're writing to the canvas as soon as the image is loaded, however you're trying to read from the canvas as soon as a file is selected, move:

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

    into the image.onload and after the context.drawImage(image, 0, 0, canvas.width, canvas.height) call so you're sure there is image data that you can read.

    It should look something like this:

    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);
    }