ImageData byte length is not a multiple of 4 * width

我们两清 提交于 2019-12-10 14:11:49

问题


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:


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


来源:https://stackoverflow.com/questions/38556730/imagedata-byte-length-is-not-a-multiple-of-4-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!