Get color palette of an image using ColorThief

Colton Shawn O'Connor
2 min readApr 1, 2021

Hello again friends. I have been working through coding bootcamp and I realized my greatest weakness has been design. I always seem to get lost on what I think looks good, artistic, sleek, etc. So to work my artistic muscle, I decided to do a color palette collector app. After scouring different libraries, I came across ColorThief.

ColorThief is a node library that can be used on the frontend with Javascript, or the backend with node. Bellow I will show you how to implement it on the frontend, and how to start getting color palettes to your hearts desire.

First you will want to install ColorThief. Instructions are on the hyperlink above. Once you’ve downloaded the node package above into your node modules, you can import it into your project w/

import ColorThief from './node_modules/colorthief/dist/color-thief.mjs'const colorThief = new ColorThief();

The way ColorThief works is that it actually pulls the photo data from the <img> HTLM element. So using DOM manipulation, you can grab that element and get it’s main color by doing the following

const $imageSection = document.querySelector('#image-section')const $image = document.createElement('img')$image.src = './image_link'$image.crossOrigin="Anonymous"
const numOfPal = 7

const mainColor = colorThief.getColor($image)
const colorPalettes = colorThief.getPalettes($image, numOfPal)
$imageSection.append($image)

There you have it! mainColor now contains the 3 RGB values of the main color in the photo, and colorPalettes contains 7 arrays of RGB color palettes. It is worth noting that you may run into some CORS errors without setting the image’s cross origin to anonymous.

In my project I implemented ColorThief in order to get color palettes of film posters. Using theMovieDb’s massive database, I was able to test out colorThief on thousands of photos, and it was even simple enough to implement uploaded photos color palettes. If you would like to look at the full work on my project you can find the GitHub repo here.

Thank you for reading and happy coloring.

--

--