ColorThief는 이미지에서 가장 대표적인 색상(주요 색상)을 추출하는 JavaScript 라이브러리다. 웹사이트나 앱에서 동적으로 이미지의 주요 색상을 분석하여 배경색, 테마 색상 등으로 활용할 수 있다. 별도의 서버 없이 클라이언트 측에서 즉시 처리되며, 매우 가볍고 빠른 색상 추출이 특징이다.
<script src="https://chir.ag/projects/ntc/ntc.js"></script>
<script src="https://chir.ag/projects/colorThief/colorThief.js"></script>
npm install colorthief
import ColorThief from 'colorthief';
const img = new Image();
img.src = 'image.jpg';
img.onload = function() {
const colorThief = new ColorThief();
const dominantColor = colorThief.getColor(img);
console.log(dominantColor); // [255, 100, 50]
};
function rgbToHex(rgb) {
return '#' + rgb.map(x => {
const hex = x.toString(16);
return hex.length === 1 ? '0' + hex : hex;
}).join('').toUpperCase();
}
const dominantColor = [255, 100, 50];
const hexColor = rgbToHex(dominantColor);
console.log(hexColor); // #FF6432
const img = new Image();
img.src = 'image.jpg';
img.onload = function() {
const colorThief = new ColorThief();
const palette = colorThief.getPalette(img, 5); // 5개 색상 추출
console.log(palette);
// [[255, 100, 50], [200, 150, 100], ...]
};
외부 도메인의 이미지를 사용할 때는 crossOrigin 속성을 설정해야 한다.
const img = new Image();
img.crossOrigin = 'Anonymous'; // 필수!
img.src = 'https://example.com/image.jpg';
img.onload = function() {
const colorThief = new ColorThief();
const color = colorThief.getColor(img);
};
항상 onload 콜백 또는 Promise를 사용해야 한다.
// ❌ 위험 - 이미지가 로드되지 않았을 수 있음
const img = new Image();
img.src = 'image.jpg';
const color = new ColorThief().getColor(img);
// ✅ 안전 - 이미지 로드 후 처리
function getImageColor(src) {
return new Promise((resolve) => {
const img = new Image();
img.crossOrigin = 'Anonymous';
img.src = src;
img.onload = () => {
const color = new ColorThief().getColor(img);
resolve(color);
};
img.onerror = () => {
resolve(null); // 에러 처리
};
});
}
const color = await getImageColor('image.jpg');
팔레트 추출 시 색상 개수를 너무 많이 설정하면 성능 저하가 발생할 수 있다.
// 권장: 3~8개 색상
const palette = colorThief.getPalette(img, 5);
// 과도한 색상 개수는 피하기
const tooMany = colorThief.getPalette(img, 100); // ❌ 느림
function getBrightnessOfRgb(rgb) {
return (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
}
const img = new Image();
img.crossOrigin = 'Anonymous';
img.src = 'image.jpg';
img.onload = function() {
const colorThief = new ColorThief();
const palette = colorThief.getPalette(img, 5);
// 가장 밝은 색 찾기
const brightestColor = palette.reduce((prev, current) =>
getBrightnessOfRgb(current) > getBrightnessOfRgb(prev) ? current : prev
);
console.log('가장 밝은 색:', brightestColor);
};
function getContrastColor(rgb) {
const brightness = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
return brightness > 128 ? '#000000' : '#FFFFFF';
}
const dominantColor = [255, 100, 50];
const textColor = getContrastColor(dominantColor);
// 밝은 배경에는 검은색 텍스트, 어두운 배경에는 흰색 텍스트
| 기능 | ColorThief | Vibrant.js | TinyColor | Canvas 수동 분석 |
|---|---|---|---|---|
| 📦 크기 | ~2KB | ~5KB | ~2KB | N/A |
| 🔥 속도 | 매우 빠름 | 빠름 | 중간 | 느림 |
| 🎨 색상 추출 | 주요 색상 | 팔레트 | 색상 변환 | 커스텀 |
| 💾 의존성 | 없음 | 없음 | 없음 | 없음 |
| 🔧 기능 | 제한적 | 풍부 | 풍부 | 커스텀 |
| 🎯 추천 용도 | 빠른 테마 | 상세 분석 | 색상 변환 | 복잡한 분석 |
ColorThief는 이미지에서 빠르고 간단하게 주요 색상을 추출하고 싶을 때 최고의 선택이다. 음악 플레이어, 영화 앱, 쇼핑몰 등에서 동적 테마 색상을 적용하기에 완벽하다. 가볍고 의존성이 없어서 프로젝트에 부담을 주지 않으면서도 강력한 기능을 제공한다.
다만 CORS 정책을 항상 염두에 두고, 이미지 로딩이 완료된 후에 색상 추출을 처리해야 한다는 점을 기억하자.