最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ImageData byte length is not a multiple of 4 * width - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Feb 3, 2022 at 17:08 Yves M. 31k24 gold badges109 silver badges149 bronze badges asked Jul 24, 2016 at 20:59 Get Off My LawnGet Off My Lawn 36.4k46 gold badges197 silver badges374 bronze badges 5
  • google./search?q=632028%2F720 – Blorgbeard Commented Jul 24, 2016 at 21:02
  • @blorgebeard: 1 upvote :) – Jonas Wilms Commented Jul 24, 2016 at 21:03
  • when I did it on my calculator I was getting this: 158007 – Get Off My Lawn Commented Jul 24, 2016 at 21:04
  • I don't know how you came up with that, but 158007*4=632028. Anyway, The error is saying that 632028/(720*4) needs to be a round number. – Blorgbeard Commented Jul 24, 2016 at 21:07
  • I was dividing by 4 not 720. I am using electrons nativeImage.toPNG() It must not be returning the alpha values. – Get Off My Lawn Commented Jul 24, 2016 at 21:09
Add a ment  | 

2 Answers 2

Reset to default 3

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

Height and Width of canvas must be eqaul in both Input canvas and output ImgData in which you are converting into.

const frame = new ImageData(clampedArray, width, height);

发布评论

评论列表(0)

  1. 暂无评论