Download the PHP package ksubileau/color-thief-php without Composer

On this page you can find all versions of the php package ksubileau/color-thief-php. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?
ksubileau/color-thief-php
Rate from 1 - 5
Rated 5.00 based on 1 reviews

Informations about the package color-thief-php

Color Thief PHP

Latest Stable Version Build Status GitHub issues Packagist License

A PHP library for grabbing the dominant color or a representative color palette from an image.

It is a PHP port of the Color Thief Javascript library, using the MMCQ (modified median cut quantization) algorithm from the Leptonica library.

See examples


Why Color Thief?

Extracting meaningful colors from an image unlocks a surprising range of use cases: generating dynamic themes that match a user's uploaded avatar, building visually coherent product cards from cover art, creating adaptive UI backgrounds for music or video players, or simply analyzing the dominant hues of a dataset of images.

Color Thief PHP does this for you, without any manual color-picking, and returns results in the color format that suits you: hex, CSS rgb(), HSL, OKLCH, CMYK, or a plain integer. You can ask for a single dominant color, a ranked palette of up to 20 colors, or semantic swatches (Vibrant, Muted, DarkVibrant, etc.).


Requirements


Getting started

Install via Composer

The recommended way to install Color Thief is through Composer:

Get the dominant color

All functionality is exposed through the ColorThief\ColorThief class. Instantiate it once and reuse it across multiple images.

getColor() returns a RgbColor object (or null if no color could be extracted), with a set of utility methods to get the color representation that suits you.

Get a color palette

getPalette() returns a ColorPalette object, which is countable, iterable, and array-accessible. Colors are ordered from most to least dominant.

Get semantic swatches

getSwatches() classifies the palette colors into up to six named roles: vibrant, muted, darkVibrant, darkMuted, lightVibrant, and lightMuted. Each property holds an RgbColor or null if no palette color matched that role.

Accepted image sources

All three methods accept the same types for the $sourceImage parameter:

Note: Loading images from URLs is no longer supported in v3. If you need to process a remote image, fetch it yourself before passing the content to Color Thief (see Migrating from v2 to v3).


Working with Color Objects

Every method returns RgbColor objects (or collections of them), with a rich set of chainable conversion and utility methods.

Converting a single color

Available conversion targets from any color object: toRgb(), toOklch(), toHsl(), toHsv(), toCmyk().

Converting a palette

ColorPalette mirrors the same conversion methods, applied to all colors at once:


Advanced Configuration

Constructor options

All configuration is passed to the ColorThief constructor. Every parameter is optional and falls back to a sensible default:

Option Type Default Description
quality int 10 Pixel sampling rate. 1 analyzes every pixel (highest quality, slowest), 10 samples every 10th pixel.
whiteThreshold int 250 Pixels with R, G, and B all above this value are ignored. Set to 255 to disable white filtering
alphaThreshold int 125 Pixels with alpha below this value are ignored (0 = fully transparent, 255 = fully opaque). Set to 0 to include transparent pixels
minSaturation float 0 Pixels with HSV saturation below this ratio (0–1) are ignored. Set to 0 to disable
colorSpace ColorSpace ColorSpace::Oklch Color space used for internal quantization. ColorSpace::Oklch produces perceptually uniform palettes.
preferredAdapter AdapterInterface\|string\|null null Force using a specific image adapter: 'Gd', 'Imagick', 'Gmagick', or a custom AdapterInterface instance. Default null value means automatically choosing an available adapter

Overriding options per call with with()

ColorThief instances are immutable. If you need different settings for a specific call without affecting the base configuration, use with() by calling it with named arguments. It accepts the exact same parameters as the constructor and returns a new instance with only the specified options overridden. The original instance is left unchanged.

Adjusting pixel filters

Restricting extraction to a region

Use ImageRegion to analyze only a rectangular crop of the image:


API Reference

ColorThief

Methods

getColor(mixed $sourceImage, ?ImageRegion $region = null): ?RgbColor Returns the single most dominant color, or null if the image yields no usable pixels.

getPalette(mixed $sourceImage, int $colorCount = 10, ?ImageRegion $region = null): ColorPalette<RgbColor> Returns a palette of dominant colors (2–20). Colors are ordered most to least dominant.

getSwatches(mixed $sourceImage, ?ImageRegion $region = null): ColorSwatches Returns semantic swatches classified into six named roles: Vibrant, Muted, DarkVibrant, DarkMuted, LightVibrant, and LightMuted.

with(...): self Returns a new ColorThief instance with the specified options overridden. All arguments are optional and default to the current instance's setting.

ColorPalette<TColor>

An immutable, ordered, array-accessible collection of color objects.

Method Returns Description
count() int Number of colors in the palette
isEmpty() bool True if the palette has no colors
toRgb() ColorPalette<RgbColor> Convert the palette to sRGB colorspace
toOklch() ColorPalette<OklchColor> Convert the palette to OKLCH colorspace
toHsl() ColorPalette<HslColor> Convert the palette to HSL colorspace
toHsv() ColorPalette<HsvColor> Convert the palette to HSV colorspace
toCmyk() ColorPalette<CmykColor> Convert the palette to CMYK colorspace
toArray() list<array> Component arrays in current colorspace
toInt() list<int> Packed RGB integers
toHex(string $prefix = '') list<string> Hex strings, e.g. ["#622a83", ...]
toCss() list<string> CSS strings using the colorspace's native notation
toString() list<string> String representation of each color in its current colorspace
map(callable $fn) array Apply a callback to each color
reduce(callable $fn, $initial) mixed Reduce palette to a single value

ColorPalette implements ArrayAccess, Countable, and IteratorAggregate, so it supports foreach, count(), and $palette[0] access.

Color classes

All color classes (RgbColor, HslColor, HsvColor, OklchColor, CmykColor) share these members.

Population and weight

Method Returns Description
population() int Pixel count this color represents in the source image (among the sampled pixels)
proportion() float Fraction of analyzed pixels (0-1)

Conversions

Method Returns Description
toRgb() RgbColor Convert to sRGB
toOklch() OklchColor Convert to OKLCH
toHsl() HslColor Convert to HSL
toHsv() HsvColor Convert to HSV
toCmyk() CmykColor Convert to CMYK
toArray() array Components in native colorspace order
toInt() int Packed (r << 16 \| g << 8 \| b) integer
toHex(string $prefix = '') string Hex string, e.g. "622a83" or "#622a83"
toCss() string CSS functional notation (rgb(), hsl(), oklch())
toString() string String representation in the current colorspace.
__toString() string Same as toString()

Contrast and accessibility helpers

Method Returns Description
luminance() float WCAG 2.x relative luminance (0 = black, 1 = white)
isDark() bool True when luminance ≤ 0.179
isLight() bool True when luminance > 0.179
textColor() RgbColor The recommended foreground text color (black or white) that gives better contrast on this background

Channel accessors (specific per colorspace implementation)

RgbColor
Method Returns Description
red() int Red channel (0–255)
green() int Green channel (0–255)
blue() int Blue channel (0–255)
HslColor
Method Returns Description
hue() float Hue angle in degrees (0–360)
saturation() float Saturation (0–1)
lightness() float Lightness (0–1)
HsvColor
Method Returns Description
hue() float Hue angle in degrees (0–360)
saturation() float Saturation (0–1)
value() float Value / brightness (0–1)
OklchColor
Method Returns Description
lightness() float Lightness (0–1)
chroma() float Chroma / colorfulness (0–~0.4)
hue() float Hue angle in degrees (0–360)
CmykColor
Method Returns Description
cyan() float Cyan channel (0–1)
magenta() float Magenta channel (0–1)
yellow() float Yellow channel (0–1)
black() float Key/Black channel (0–1)

ColorSwatches

Returned by getSwatches(). All properties are public and readonly.

Property Type Description
$vibrant ?RgbColor Bright, saturated, mid-lightness color
$muted ?RgbColor Desaturated, mid-lightness color
$darkVibrant ?RgbColor Bright, saturated, dark color
$darkMuted ?RgbColor Desaturated, dark color
$lightVibrant ?RgbColor Bright, saturated, light color
$lightMuted ?RgbColor Desaturated, light color

Any property may be null if no palette color qualified for that role.

ImageRegion

Defines a rectangular crop for color extraction.

All properties are public and readonly. width and height default to null, meaning the region extends to the image's right and bottom edges respectively.

Exceptions

All exceptions live under ColorThief\Exception\ and extend a common base:

Class Thrown when
NotReadableException The image source cannot be loaded (file not found, unsupported format, URL passed)
InvalidArgumentException A parameter is out of the allowed range (e.g. colorCount outside 2–20, region out of bounds)
NotSupportedException The requested operation is not supported by the active image adapter
RuntimeException An unexpected error occurs during image processing

Migrating from v2.x to v3.x

ColorThief PHP v3.x brings major changes to the library's API, which has been thoroughly redesigned and modernized. Here's everything you need to perform the update.

The class is now instantiated, not called statically

The most visible change: ColorThief is no longer a class with static methods. You instantiate it and call methods on the instance.

Configuration is passed to the constructor, not as method arguments

In v2, options like quality and output format were passed as positional arguments to each method call. In v3, all configuration lives on the ColorThief instance. Use with() to derive variants.

The $format parameter has been removed

v2's getColor() and getPalette() accepted a $format string ('rgb', 'hex', 'int', 'array', 'obj') to control the return type. In v3, methods always return typed color objects. Convert to any format you need using the conversion methods.

RGB channel getters have been renamed

v2 exposed getRed(), getGreen(), and getBlue() on the color object. In v3 these are red(), green(), and blue().

URL loading has been removed

Passing a URL string to getColor() or getPalette() will now throw a NotReadableException. URL fetching was removed to prevent Server-Side Request Forgery (SSRF) vulnerabilities.

Fetch the image yourself and pass the binary content:

OKLCH is now the default quantization color space

v3 uses OKLCH internally by default, which produces more perceptually uniform palettes. If your application depends on the exact palette output of v2, you can restore the old behavior:

Maximum palette size reduced to 20

getPalette() now accepts a colorCount between 2 and 20 (v2 allowed up to 256). Requests above 20 will throw an InvalidArgumentException.

Edge-case behavior for degenerate images

In v2, fully transparent, fully white, or single-color images could throw exceptions. In v3 they return a graceful result instead: a single-color palette containing black (transparent images), white (all-white images), or the single color itself.

Region parameter replaces positional $area array

The optional area/region parameter in v2 was an associative array. In v3 it is a typed ImageRegion object, passed as a named argument.


Credits

Author

by Kevin Subileau kevinsubileau.fr

Based on the fabulous work done by Lokesh Dhakar lokeshdhakar.com twitter.com/lokesh

Thanks

License

Licensed under the MIT License.


All versions of color-thief-php with dependencies

PHP Build Version
Package Version
Requires php Version ^8.2
ext-fileinfo Version *
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package ksubileau/color-thief-php contains the following files

Loading the files please wait ...