context.getImageData().data 对超过某个点的像素返回 0

context.getImageData().data returning 0 for pixels past a certain point

我正在使用 getImageData() 来检索 .jpg 图像的像素数据。该功能非常适合小图像,但不适用于大图像(比如大约 240x240 及以上)。对于较大的图像,它最终只会为超过某个点的所有像素返回 0。

图像绘制完美,我的用例在其他地方提到的限制范围内,允许的宽度和高度数以万计。

function showImage(fileReader) {
    var img = document.getElementById("myImage");  
    img.onload = () => getImageData(img);
    img.src = fileReader.result; 
}

function getImageData(img) {
    ctx.drawImage(img, 0, 0);
    let imageArr = ctx.getImageData(0, 0, img.width, img.height).data;
    imageHeight = img.height;
    imageWidth = img.width;

    console.log(imageArr);

我似乎找不到关于这个确切问题的任何其他帖子。我没有收到任何控制台错误。

我正在做的事情有问题吗?我怎样才能克服这个问题?

您可能只是忘记在将图像绘制到 canvas...

之前将 canvas width/height 设置为与图像相同的大小
ctx.canvas.width = img.width
ctx.canvas.height = img.height
ctx.getImageData(...

无论如何,这是一种使用 OffscreenCanvas + createImageBitmap 的现代方法
(这使得 运行 它可以在网络工作者中使用)

/**
 * @param {ImageBitmap} bitmap
 */
function getClampedArr (bitmap) {
  // Set the canvas to be the same size as the image
  const ctx = new OffscreenCanvas(bitmap.width, bitmap.height).getContext('2d')
  ctx.drawImage(bitmap, 0, 0)
  return ctx.getImageData(0, 0, bitmap.width, bitmap.height).data
}

// Simulate a file u would normaly get from a file input
const url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
fetch(url).then(r => r.blob()).then(file => 
    
  // This is what you want to do with your file
  createImageBitmap(file)
    .then(getClampedArr)
  
).then(console.log, console.error)