使用 canvas 确定图像的亮度

Determining the brightness of an image using canvas

我有一个循环遍历图像像素的函数,可以将图像的平均值 "brightness" 确定为 0(黑色)- 之间的数字]255(白色).

问题是在测试过程中,我发现虽然全黑的图像 (#000000) 会正确 return 0,但全白的图像(#FFFFFF) return 是 200 左右的数字,而不是 255。我错过了什么吗?

这是我的函数,如有任何帮助,我们将不胜感激!

function getBrightness(imageSrc, callback) {
  const img = document.createElement("img");
  img.src = imageSrc;
  img.style.display = "none";
  document.body.appendChild(img);
  let colorSum = 0;

    img.onload = function() {
      const canvas = document.createElement("canvas");
      canvas.width = this.width;
      canvas.height = this.height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(this, 0, 0);

      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const data = imageData.data;
      let r, g, b, avg;

      for(let x=0, len=data.length; x<len; x+=4) {
        r = data[x];
        g = data[x+1];
        b = data[x+2];
        avg = Math.floor((r+g+b) / 3);
        colorSum += avg;
      }

      const brightness = Math.floor(colorSum / (this.width * this.height));
      callback(brightness);
    }
}

抱歉,正如下面的代码片段所证明的,您提到的图片的结果是 255。 也许您想检查一下您在测试中使用的是什么文件?您可能使用了错误的文件...

function getBrightness(imageSrc, callback) {
  const img = document.createElement("img");
  img.src = imageSrc;
  img.crossOrigin = 'anonymous';
  img.style.display = "none";
  document.body.appendChild(img);
  let colorSum = 0;

    img.onload = function() {
      const canvas = document.createElement("canvas");
      canvas.width = this.width;
      canvas.height = this.height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(this, 0, 0);

      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const data = imageData.data;
      let r, g, b, avg;

      for(let x=0, len=data.length; x<len; x+=4) {
        r = data[x];
        g = data[x+1];
        b = data[x+2];
        avg = Math.floor((r+g+b) / 3);
        colorSum += avg;
      }

      const brightness = Math.floor(colorSum / (this.width * this.height));
      callback(brightness);
    }
};


getBrightness(
    'https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Solid_white.svg/768px-Solid_white.svg.png', 
    (b)=>console.log(b));

为了避免 cors 安全消息,我刚刚包含了行 img.crossOrigin = 'anonymous';