kodie
12/27/2016 - 5:40 PM

Returns a number between 1 and 255 specifying the image brightness.

Returns a number between 1 and 255 specifying the image brightness.

var promise = require('promise');

function getImgBrightness(image, x, y, w, h) {
  var jimp = require('jimp');

  return new Promise(function (fulfill, reject){
    jimp.read(image, function(error, image){
      if (!error) {
        if (!x) { x = 0; }
        if (!y) { y = 0; }
        if (!w) { w = image.bitmap.width; }
        if (!h) { h = image.bitmap.height; }
        var colorSum = 0;

        image.scan(x, y, w, h, function(x, y, idx) {
          var r = this.bitmap.data[idx + 0];
          var g = this.bitmap.data[idx + 1];
          var b = this.bitmap.data[idx + 2];
          var avg = Math.floor((r + g + b) / 3);
          colorSum += avg;
        });

        var brightness = Math.floor(colorSum / (w * h));
        fulfill(brightness);
      } else { reject(error); }
    });
  });
}

getImgBrightness('image.jpg')
  .then(function(b){ console.log(b); });