lokesh / color-thief

Grab the color palette from an image using just Javascript. Works in the browser and in Node.
https://lokeshdhakar.com/projects/color-thief/
MIT License
12.46k stars 1.31k forks source link

Ocassional NPE in ColorThief.prototype.getColor #131

Open DallanQ opened 6 years ago

DallanQ commented 6 years ago

Every once in awhile, getPalette returns null, which causes palette[0] to throw an error.

ColorThief.prototype.getColor = function(sourceImage, quality) {
    var palette = this.getPalette(sourceImage, 5, quality);
    var dominantColor = palette[0];
    return dominantColor;
};

Any ideas what to do when getPalette returns null? Is there a decent default value for dominantColor?

jazott3 commented 5 years ago

I think it's related to this function returning an empty array: https://github.com/lokesh/color-thief/blob/master/src/core.js#L1-L20

Which is then fed to quantize as pixels and caught here: https://github.com/lokesh/quantize/blob/master/src/quantize.js#L400

setting the value of palette to false.

At least, this is what is causing an NPE for me on the same line. I'm not yet sure what the right fix is. Maybe initializing const pixelArray = [[127, 127, 127]]; for a gray value. I haven't yet figured out why my input is failing all of the checks here: https://github.com/lokesh/color-thief/blob/master/src/core.js#L13-L17

jharris4 commented 5 years ago

We're hitting this issue as well, would be great to have a fix