使用画布确定图像的亮度

时间:2018-07-09 20:45:05

标签: javascript canvas getimagedata

我有一个循环遍历图像像素的函数,以确定图像的平均“亮度”为介于 0 (黑色)- 255 (白色)之间的数字

问题是在测试过程中,我发现虽然全黑(#000000)的图像会正确返回 0 ,而全白(#FFFFFF)的图像会返回 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);
    }
}

1 个答案:

答案 0 :(得分:0)

对不起,但是如下面的代码片段所示,您提到的图像结果为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));

我只是加入了img.crossOrigin = 'anonymous';行,以避免出现cors安全消息。