@devsola/image-color
v1.0.1
Published
Extract dominant color from an image (URL, File, or HTMLImageElement)
Readme
# 🎨 @devsola/image-color
Extract the dominant color from any image — fast, lightweight, and TypeScript-first.
- ✅ Works with image URLs
- ✅ Supports `File` objects
- ✅ Accepts `HTMLImageElement`
- ✅ Zero runtime dependencies
- ✅ ESM + CJS support
- ✅ Fully typed
🔗 **Live Demo:** https://shade-spotter.netlify.app/
📦 **npm:** https://www.npmjs.com/package/@devsola/image-color
---
## 📦 Installation
```bash
npm install @devsola/image-color
```
or
```bash
yarn add @devsola/image-color
```
or
```bash
pnpm add @devsola/image-color
```
---
## 🚀 Usage
### Using an Image URL
```ts
import { getDominantColor } from "@devsola/image-color";
const color = await getDominantColor(
"https://example.com/image.jpg"
);
console.log(color);
// {
// rgb: [139, 92, 55],
// hex: "#8b5c37"
// }
```
---
### Using a File Input
```ts
import { getDominantColor } from "@devsola/image-color";
const input = document.querySelector("input[type='file']");
input?.addEventListener("change", async (e) => {
const file = (e.target as HTMLInputElement).files?.[0];
if (!file) return;
const color = await getDominantColor(file);
console.log(color.hex);
});
```
---
### Using an HTMLImageElement
```ts
const img = document.querySelector("img");
const color = await getDominantColor(img!);
console.log(color.rgb);
```
---
## ⚙️ API
### `getDominantColor(input, options?)`
#### Parameters
| Parameter | Type | Required | Description |
|------------|------|----------|-------------|
| `input` | `string \| File \| HTMLImageElement` | ✅ | Image source |
| `options.quality` | `number` | ❌ | Pixel sampling rate (default: `10`) |
| `options.precision` | `number` | ❌ | Color grouping strength (default: `16`) |
#### Returns
```ts
{
rgb: [number, number, number];
hex: string;
}
```
---
## 🧠 How It Works
- Downscales the image for performance (~100x100)
- Extracts pixel data via the Canvas API
- Ignores transparent pixels
- Reduces color precision to merge similar tones
- Uses frequency mapping to determine the dominant color
---
## ⚠️ CORS Notice
If using external image URLs:
The image must allow cross-origin access.
If you encounter a canvas security error:
- Host the image yourself
- Use a proxy
- Or provide a `File` instead
---
## 🏗 Build & Development
```bash
npm install
npm run build
```
Outputs:
- ESM build
- CommonJS build
- Type declarations
---
## 📁 Project Structure
```
src/
core/
utils/
types.ts
index.ts
```
Built using:
- TypeScript
- tsup (dual ESM + CJS build)
---
## 🌍 Use Cases
- Dynamic UI theming
- Avatar background generation
- Brand color extraction
- Image-based gradients
- Social card styling
- Media previews
---
## 📜 License
MIT
---
## 👤 Author
Devsola
- npm: https://www.npmjs.com/package/@devsola/image-color
- Demo: https://shade-spotter.netlify.app/