Skip to content Skip to sidebar Skip to footer

Determining The Brightness Of An Image Using Canvas

I have a function that loops through an image's pixels to determine the average 'brightness' of the image as a number between 0 (black) - 255 (white). The problem is during testing

Solution 1:

Sorry, but as the snippet below proves, the result for the image you mentioned is 255. Maybe you want to check out what file you were using in the tests ? you're probably using a wrong file...

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

I just included the line img.crossOrigin = 'anonymous'; in order to avoid the cors security message.

Post a Comment for "Determining The Brightness Of An Image Using Canvas"