Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageData byte length is not a multiple of 4 * width

I am having an issue with creating ImageData. I am getting the following error message:

Uncaught IndexSizeError: Failed to construct 'ImageData': The input data byte length is not a multiple of (4 * width).

Here is the method that I am running:

public setPixelData(data: Buffer, width: number, height: number) {
    var imageData = new ImageData(new Uint8ClampedArray(data), width, height);
    this.canvas.getContext('2d').putImageData(imageData, 0, 0);
}

I have dumped the data and this is what is showing:

data = Uint8Array[632028]
width = 720
height = 720

So, what would be the cause of this error, and how can it be fixed?

like image 672
Get Off My Lawn Avatar asked Jul 24 '16 20:07

Get Off My Lawn


1 Answers

I had the same problem, apparently the array size needs to be the multiple of width, height and 4. As Daniel pointed out correctly the multiplication with 4 is due to the RGBA color space, which consists of the four channels red, green, blue, and alpha.

So for your case: 720 * 720 * 4 equals 2073600

var width = 720, height = 720;
var data = new ImageData(
  new Uint8ClampedArray(4 * width * height),
  720,
  720
);
console.log(data);
like image 112
Robbendebiene Avatar answered Nov 17 '22 11:11

Robbendebiene