PHPackages                             abderrahimghazali/color-palette-extractor - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Image &amp; Media](/categories/media)
4. /
5. abderrahimghazali/color-palette-extractor

ActiveLibrary[Image &amp; Media](/categories/media)

abderrahimghazali/color-palette-extractor
=========================================

Extract dominant colors from images with PHP

v1.0.0(11mo ago)12MITPHPPHP &gt;=7.4

Since Jun 9Pushed 11mo agoCompare

[ Source](https://github.com/abderrahimghazali/color-palette-extractor)[ Packagist](https://packagist.org/packages/abderrahimghazali/color-palette-extractor)[ Docs](https://github.com/abderrahimghazali/color-palette-extractor)[ RSS](/packages/abderrahimghazali-color-palette-extractor/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (1)Versions (2)Used By (0)

Color Palette Extractor
=======================

[](#color-palette-extractor)

A fast and simple PHP library to extract dominant colors from images using GD extension.

Features
--------

[](#features)

- 🎨 Extract dominant colors from any image
- 🚀 Fast processing with quality control
- 📊 Get color percentages and brightness analysis
- 🎯 Multiple output formats (HEX, RGB, HSL)
- 🔍 Smart similar color filtering
- 🖼️ Support for JPEG, PNG, GIF, WebP
- 💡 Complementary color generation
- 🎲 Zero dependencies (except GD)

Installation
------------

[](#installation)

```
composer require abderrahimghazali/color-palette-extractor
```

**Requirements:**

- PHP 7.4+
- GD extension

Quick Start
-----------

[](#quick-start)

```
use ColorPaletteExtractor\ColorPalette;

// Extract 5 dominant colors
$palette = ColorPalette::fromImage('path/to/image.jpg');
$colors = $palette->getDominant(5);
// ['#ff5733', '#33ff57', '#3357ff', '#ffff33', '#ff33ff']

// Get primary color
$primary = $palette->getPrimary();
// '#ff5733'

// With percentages
$detailed = $palette->getPaletteWithPercentages(3);
// [
//   ['color' => '#ff5733', 'percentage' => 35.2],
//   ['color' => '#33ff57', 'percentage' => 28.1],
//   ['color' => '#3357ff', 'percentage' => 15.7]
// ]
```

Advanced Usage
--------------

[](#advanced-usage)

### Different Output Formats

[](#different-output-formats)

```
// RGB format
$rgbColors = ColorPalette::fromImage('image.jpg')
    ->format('rgb')
    ->getDominant(3);
// [[255, 87, 51], [51, 255, 87], [51, 87, 255]]

// HSL format
$hslColors = ColorPalette::fromImage('image.jpg')
    ->format('hsl')
    ->getDominant(3);
// [[9, 100, 60], [129, 100, 60], [219, 100, 60]]
```

### Quality Control

[](#quality-control)

```
// Higher quality = slower but more accurate
$palette = ColorPalette::fromImage('image.jpg')
    ->quality(8) // 1-10 scale
    ->getDominant(5);

// Lower quality = faster processing
$fastPalette = ColorPalette::fromImage('large-image.jpg')
    ->quality(3)
    ->getDominant(5);
```

### Image Analysis

[](#image-analysis)

```
$palette = ColorPalette::fromImage('image.jpg');

// Check if image is light or dark
$brightness = $palette->getBrightness();
// 'light' or 'dark'

// Get complementary colors
$complementary = $palette->getComplementary(3);
// Colors that complement the dominant ones
```

### From Image Data

[](#from-image-data)

```
// From raw image data
$imageData = file_get_contents('https://example.com/image.jpg');
$palette = ColorPalette::fromData($imageData);
$colors = $palette->getDominant(5);

// From uploaded file
$palette = ColorPalette::fromData($_FILES['image']['tmp_name']);
```

Method Reference
----------------

[](#method-reference)

### Core Methods

[](#core-methods)

#### `getDominant(int $count = 5, bool $excludeSimilar = true): array`

[](#getdominantint-count--5-bool-excludesimilar--true-array)

Extract dominant colors from the image.

#### `getPrimary(): string`

[](#getprimary-string)

Get the single most dominant color.

#### `getPaletteWithPercentages(int $count = 5): array`

[](#getpalettewithpercentagesint-count--5-array)

Get colors with their percentage coverage.

#### `getBrightness(): string`

[](#getbrightness-string)

Determine if image is 'light' or 'dark'.

#### `getComplementary(int $count = 5): array`

[](#getcomplementaryint-count--5-array)

Get complementary colors for the palette.

### Configuration Methods

[](#configuration-methods)

#### `quality(int $quality): self`

[](#qualityint-quality-self)

Set extraction quality (1-10, higher = more accurate but slower).

#### `format(string $format): self`

[](#formatstring-format-self)

Set output format: 'hex', 'rgb', or 'hsl'.

### Static Factory Methods

[](#static-factory-methods)

#### `ColorPalette::fromImage(string $path): self`

[](#colorpalettefromimagestring-path-self)

Create instance from image file path.

#### `ColorPalette::fromData(string $data): self`

[](#colorpalettefromdatastring-data-self)

Create instance from raw image data.

Real-World Examples
-------------------

[](#real-world-examples)

### Website Theme Generator

[](#website-theme-generator)

```
function generateTheme($logoPath) {
    $palette = ColorPalette::fromImage($logoPath);

    return [
        'primary' => $palette->getPrimary(),
        'secondary' => $palette->getDominant(2)[1] ?? '#cccccc',
        'accent' => $palette->getComplementary(1)[0],
        'brightness' => $palette->getBrightness()
    ];
}
```

### Product Color Analysis

[](#product-color-analysis)

```
function analyzeProductImage($imagePath) {
    $palette = ColorPalette::fromImage($imagePath)
        ->quality(7); // High quality for product images

    $analysis = $palette->getPaletteWithPercentages(5);

    return [
        'dominant_colors' => $analysis,
        'is_colorful' => count($analysis) > 3,
        'brightness' => $palette->getBrightness(),
        'primary_color' => $palette->getPrimary()
    ];
}
```

### Automatic Color Tagging

[](#automatic-color-tagging)

```
function generateColorTags($imagePath) {
    $colors = ColorPalette::fromImage($imagePath)
        ->format('hsl')
        ->getDominant(3);

    $tags = [];
    foreach ($colors as $hsl) {
        $hue = $hsl[0];
        if ($hue < 30) $tags[] = 'red';
        elseif ($hue < 90) $tags[] = 'yellow';
        elseif ($hue < 150) $tags[] = 'green';
        elseif ($hue < 210) $tags[] = 'cyan';
        elseif ($hue < 270) $tags[] = 'blue';
        elseif ($hue < 330) $tags[] = 'magenta';
        else $tags[] = 'red';
    }

    return array_unique($tags);
}
```

Error Handling
--------------

[](#error-handling)

```
try {
    $palette = ColorPalette::fromImage('nonexistent.jpg');
} catch (\Exception $e) {
    echo "Error: " . $e->getMessage();
}

// Common exceptions:
// - "GD extension is required for color extraction"
// - "Image file not found: path/to/image.jpg"
// - "Invalid image file"
// - "Unsupported image type: image/bmp"
```

Performance Tips
----------------

[](#performance-tips)

1. **Use quality control**: Lower quality (1-3) for thumbnails, higher (7-10) for detailed analysis
2. **Process smaller images**: The library automatically resizes, but smaller sources are faster
3. **Cache results**: Color extraction is CPU-intensive, cache results when possible
4. **Exclude similar colors**: Keep `excludeSimilar=true` for cleaner palettes

Supported Image Formats
-----------------------

[](#supported-image-formats)

- JPEG (`.jpg`, `.jpeg`)
- PNG (`.png`)
- GIF (`.gif`)
- WebP (`.webp`) - if PHP compiled with WebP support

How It Works
------------

[](#how-it-works)

1. **Image Loading**: Uses GD to load the image
2. **Resizing**: Automatically resizes to ~150px for performance
3. **Color Sampling**: Samples pixels based on quality setting
4. **Color Grouping**: Groups similar colors to reduce noise
5. **Frequency Analysis**: Counts color occurrences
6. **Filtering**: Removes rare colors and optionally similar colors
7. **Formatting**: Converts to requested output format

License
-------

[](#license)

MIT License. See LICENSE file for details.

Contributing
------------

[](#contributing)

Pull requests welcome! Please ensure tests pass:

```
composer test
```

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance52

Moderate activity, may be stable

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity36

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

337d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e1be9cf8e271987c350c614aa618f0e68c7f7409634e51f8c8fe105490899b0f?d=identicon)[abderrahim.ghazali](/maintainers/abderrahim.ghazali)

---

Top Contributors

[![abderrahimghazali](https://avatars.githubusercontent.com/u/12643883?v=4)](https://github.com/abderrahimghazali "abderrahimghazali (3 commits)")

---

Tags

color-palettecomposer-packagegd-extensionimage-processingimagegdcolorextractionpalettedominant

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/abderrahimghazali-color-palette-extractor/health.svg)

```
[![Health](https://phpackages.com/badges/abderrahimghazali-color-palette-extractor/health.svg)](https://phpackages.com/packages/abderrahimghazali-color-palette-extractor)
```

###  Alternatives

[intervention/image

PHP Image Processing

14.3k194.3M2.2k](/packages/intervention-image)[league/color-extractor

Extract colors from an image as a human would do.

1.3k4.7M18](/packages/league-color-extractor)[league/glide

Wonderfully easy on-demand image manipulation library with an HTTP based API.

2.6k51.2M116](/packages/league-glide)[ksubileau/color-thief-php

Grabs the dominant color or a representative color palette from an image.

6353.8M37](/packages/ksubileau-color-thief-php)[brianmcdo/image-palette

Extracts colors from an image and generates a color palette against a whitelist of colors.

179209.0k2](/packages/brianmcdo-image-palette)[gregwar/image

Image handling

1.0k4.1M51](/packages/gregwar-image)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
