Get dominant color from base64 encoded string using ColorThief

To install package use:

npm i color-thief --save

Here is a function you can use:

async function getImageFromBase64str(b64str) {
const img = document.createElement('img');
    await new Promise((r) => {
      img.src = b64str;
      img.onload = r;
    })
    const colorThief = new ColorThief();
    const rgba = colorThief.getColor(img, 5);
    if (!rgba) {
      return 'rgba(0,0,0,0)'; // seems to happen on white image
    } else {
      return rgbToHex(rgba[0], rgba[1], rgba[2]);
    }
}

If you need rgbToHex helper:

function rgbToHex(r, g, b) {
const hexStr = [r, g, b].map((x) => {
    const hex = x.toString(16);
    return hex.length === 1 ? `0${hex}` : hex;
  }).join('');
return `#${hexStr}`;
}

#graphics #css
0
Ivan Borshchov profile picture
Nov 25, 2021
by Ivan Borshchov
Did it help you?
Yes !
No

Best related