ImageData byte length is not a multiple of 4 * wid

2019-06-22 16:33发布

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?

1条回答
爷的心禁止访问
2楼-- · 2019-06-22 16:54

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

查看更多
登录 后发表回答