abderrahimghazali / color-palette-extractor
Extract dominant colors from images with PHP
v1.0.0
2025-06-09 16:38 UTC
Requires
- php: >=7.4
- ext-gd: *
Requires (Dev)
- phpunit/phpunit: ^9.0|^10.0
This package is auto-updated.
Last update: 2025-06-09 16:41:29 UTC
README
A fast and simple PHP library to extract dominant colors from images using GD extension.
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
composer require abderrahimghazali/color-palette-extractor
Requirements:
- PHP 7.4+
- GD extension
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
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
// 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
$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 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
Core Methods
getDominant(int $count = 5, bool $excludeSimilar = true): array
Extract dominant colors from the image.
getPrimary(): string
Get the single most dominant color.
getPaletteWithPercentages(int $count = 5): array
Get colors with their percentage coverage.
getBrightness(): string
Determine if image is 'light' or 'dark'.
getComplementary(int $count = 5): array
Get complementary colors for the palette.
Configuration Methods
quality(int $quality): self
Set extraction quality (1-10, higher = more accurate but slower).
format(string $format): self
Set output format: 'hex', 'rgb', or 'hsl'.
Static Factory Methods
ColorPalette::fromImage(string $path): self
Create instance from image file path.
ColorPalette::fromData(string $data): self
Create instance from raw image data.
Real-World Examples
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
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
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
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
- Use quality control: Lower quality (1-3) for thumbnails, higher (7-10) for detailed analysis
- Process smaller images: The library automatically resizes, but smaller sources are faster
- Cache results: Color extraction is CPU-intensive, cache results when possible
- Exclude similar colors: Keep
excludeSimilar=true
for cleaner palettes
Supported Image Formats
- JPEG (
.jpg
,.jpeg
) - PNG (
.png
) - GIF (
.gif
) - WebP (
.webp
) - if PHP compiled with WebP support
How It Works
- Image Loading: Uses GD to load the image
- Resizing: Automatically resizes to ~150px for performance
- Color Sampling: Samples pixels based on quality setting
- Color Grouping: Groups similar colors to reduce noise
- Frequency Analysis: Counts color occurrences
- Filtering: Removes rare colors and optionally similar colors
- Formatting: Converts to requested output format
License
MIT License. See LICENSE file for details.
Contributing
Pull requests welcome! Please ensure tests pass:
composer test