bensquire / php-color-extractor
A simple class to extract the primary colours from an image.
Requires
- php: ^8.3 || ^8.4
- ext-gd: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- phpstan/phpstan: ^2.0
- phpunit/phpunit: ^12.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-14 19:12:33 UTC
README
A modern PHP library to extract the dominant color palette from images.
Features
- Extract dominant colors from any image format supported by GD
- Accepts a file path, raw image data or a
GdImage - Configurable number of colors to extract
- Adjustable granularity for performance vs. accuracy tradeoff
- Fluent interface for easy chaining
- Type-safe with strict PHP 8.3+ type declarations
- Full PHPStan level max compliance
- 100% test coverage
Requirements
- PHP 8.3 or newer (tested on 8.3, 8.4 and 8.5)
- GD extension
Installation
Install via Composer:
composer require bensquire/php-color-extractor
Usage
Basic Example
<?php use PHPColorExtractor\PHPColorExtractor; $extractor = new PHPColorExtractor(); $extractor->setImage('/path/to/image.jpg'); $palette = $extractor->extractPalette(); // Returns array of hex colors, e.g., ['CC6666', 'FF9933', '66CC99', ...] print_r($palette);
Advanced Usage with Fluent Interface
<?php use PHPColorExtractor\PHPColorExtractor; $extractor = new PHPColorExtractor(); $palette = $extractor ->setImage('/path/to/image.jpg') ->setTotalColors(5) // Extract 5 colors (default: 10) ->setGranularity(10) // Check every 10th pixel (default: 5) ->extractPalette(); foreach ($palette as $color) { echo "#{$color}\n"; }
Configuration Options
setImage(string $image): self
Set the path to the image file to analyze.
Throws: Exception if the file doesn't exist.
setImageFromString(string $data): self
Set the image from raw image data, such as an uploaded file or a response body. The data is decoded straight away.
Throws: Exception if the data isn't an image GD can read.
setImageFromGd(GdImage $image): self
Set the image from an existing GD image, e.g. one you've already resized or cropped.
Each setImage*() call replaces any image set previously.
setTotalColors(int $totalColors = 10): self
Set the number of dominant colors to extract.
Default: 10
Throws: Exception if the value is less than or equal to 0.
setGranularity(int $granularity = 5): self
Set the sampling granularity. Higher values = faster but less accurate. Lower values = slower but more accurate.
Default: 5
Throws: Exception if the value is less than or equal to 0.
extractPalette(): array<int, string>
Extract and return the color palette as an array of hex color strings.
Returns: Array of hex color strings (without # prefix)
Throws: Exception if no image has been set or if image processing fails.
Examples
Web Color Palette Display
<?php use PHPColorExtractor\PHPColorExtractor; $extractor = new PHPColorExtractor(); $palette = $extractor ->setImage('uploaded-image.jpg') ->setTotalColors(8) ->extractPalette(); echo '<div class="palette">'; foreach ($palette as $color) { echo sprintf( '<div class="color" style="background-color: #%s;"></div>', $color ); } echo '</div>';
Image from a URL or Upload
The library doesn't download images itself. Fetch the image with your own HTTP client (so you control timeouts, size limits and which hosts are allowed) and pass the bytes in:
<?php use PHPColorExtractor\PHPColorExtractor; // e.g. with Guzzle $body = (string) $httpClient->get('https://example.com/photo.jpg')->getBody(); $palette = (new PHPColorExtractor()) ->setImageFromString($body) ->extractPalette();
Fast Preview (Low Accuracy)
<?php use PHPColorExtractor\PHPColorExtractor; // Quick extraction for thumbnails or previews $palette = (new PHPColorExtractor()) ->setImage('large-image.jpg') ->setTotalColors(3) ->setGranularity(20) // Sample every 20th pixel for speed ->extractPalette();
High Accuracy Analysis
<?php use PHPColorExtractor\PHPColorExtractor; // Detailed extraction for color analysis $palette = (new PHPColorExtractor()) ->setImage('artwork.jpg') ->setTotalColors(15) ->setGranularity(1) // Sample every pixel for maximum accuracy ->extractPalette();
Development
Running Tests
composer install vendor/bin/phpunit
Running Static Analysis
vendor/bin/phpstan analyse
Running All Quality Checks
vendor/bin/phpstan analyse && vendor/bin/phpunit
How It Works
The library samples pixels from the image at intervals determined by the granularity setting. It then:
- Rounds RGB values to reduce similar colors
- Counts occurrences of each color
- Sorts by frequency
- Returns the most common colors
This approach is based on this Stack Overflow answer.
Contributing
Contributions are welcome! Please ensure:
- All tests pass (
vendor/bin/phpunit) - PHPStan analysis passes at max level (
vendor/bin/phpstan analyse) - Code follows PSR-4 autoloading standards
- New features include tests
License
This library is licensed under the MIT License. See LICENSE for details.
Credits
- Ben Squire - Original author
- Inspired by Stack Overflow community
Changelog
See CHANGELOG.md for version history and changes.