PHPackages                             tomloprod/colority - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. tomloprod/colority

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

tomloprod/colority
==================

Colority is a lightweight PHP library designed to handle color transformations, validations and manipulations with ease.

v2.0.0(1mo ago)237150.6k↑38.2%91MITPHPPHP ^8.2.0CI passing

Since May 25Pushed 1mo ago2 watchersCompare

[ Source](https://github.com/tomloprod/colority)[ Packagist](https://packagist.org/packages/tomloprod/colority)[ Fund](https://www.paypal.com/paypalme/tomloprod)[ RSS](/packages/tomloprod-colority/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (10)Dependencies (8)Versions (11)Used By (1)

 [![Colority logo](./docs/colority.png "Colority - Color Engine for PHP")](./docs/colority.png)**Color Engine for PHP**

 [![PHP >= 8.2](https://camo.githubusercontent.com/6cb1ba963623afb0b5b557cc9a2ec3e8833221a9ede88d09e8a6ede86c22b5d4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d25453225383925413520382e322d3737374242343f7374796c653d666c61742d737175617265266c6f676f436f6c6f723d7768697465266c6162656c436f6c6f723d31313138323726636f6c6f723d346635623933266c6162656c3d504850)](https://www.php.net/) [![Version](https://camo.githubusercontent.com/9d0aaed56f4e32f55cb683a82f65a3ebbf829af242c0011a82d728b6ffdcfdac/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f6d6c6f70726f642f636f6c6f726974793f7374796c653d666c61742d737175617265266c6162656c3d76657273696f6e266c6162656c436f6c6f723d31313138323726636f6c6f723d7768697465)](https://packagist.org/packages/tomloprod/colority) [![CI](https://camo.githubusercontent.com/e5f2affca57b065a363c0d2b062666b37e1fe815bb6330c5fa837834cf5dbf51/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f746f6d6c6f70726f642f636f6c6f726974792f74657374732e796d6c3f6272616e63683d6d61696e267374796c653d666c61742d737175617265266c6162656c3d7465737473266c6162656c436f6c6f723d31313138323726636f6c6f723d316135333464)](https://github.com/tomloprod/colority/actions) [![Downloads](https://camo.githubusercontent.com/cfa07e1dcaf658b5251d393a620694eedca94e96b65dcff8913cd63cd3830151/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f6d6c6f70726f642f636f6c6f726974793f7374796c653d666c61742d737175617265266c6162656c3d646f776e6c6f616473266c6162656c436f6c6f723d31313138323726636f6c6f723d623135333536)](https://packagist.org/packages/tomloprod/colority) [![License](https://camo.githubusercontent.com/eaa67f7068e27b21c01de4dc4008df103665ff07cb27f24277fe3d1e1c75e838/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f746f6d6c6f70726f642f636f6c6f726974793f7374796c653d666c61742d737175617265266c6162656c3d6c6963656e7365266c6162656c436f6c6f723d31313138323726636f6c6f723d333835343364)](https://packagist.org/packages/tomloprod/colority)

**About Colority**
------------------

[](#about-colority)

**Colority** is a PHP library for working with colors. It handles conversions between RGB, HSL, Hex, and OKLCH formats, calculates WCAG-compliant contrast ratios, extracts color palettes from images, and more.

**Features**
------------

[](#features)

### Getting Started

[](#getting-started)

- **[Instantiating Color Objects](#instantiating-color-objects)**

    - Create RGB, HSL, Hex, and OKLCH color objects from strings or arrays
    - Auto-detect color format with `parse()` method
- **[Contrast Ratio (WCAG 2.0)](#contrast-ratio-wcag-20-standard)**

    - **[getBestForegroundColor](#getbestforegroundcolor)**: Pick the best color from a list of candidates
    - **[getMatchingForegroundColor](#getmatchingforegroundcolor):** Generate a foreground color that matches the background's hue
    - **[getContrastRatio](#getcontrastratio):** Calculate contrast ratios between colors
    - **[ContrastRatioScore Enum](#contrastratioscore-enum):** Validate accessibility compliance
- **[Color Validation](#color-validation)**

    - Parse and validate color strings with type-specific parsers
- **[Color Conversion](#color-conversion)**

    - Convert between RGB, HSL, Hexadecimal, and OKLCH formats
- **[Semantic Palette](#semantic-palette)**

    - Eight built-in semantic slots (primary, secondary, success, danger, warning, info, light, dark) with overrides per slot, in bulk, or by custom name

### Color Utilities

[](#color-utilities)

- **[Color Adjustments](#color-adjustments)**: Adjust brightness and saturation
- **[getImageMostCommonColor](#getimagemostcommoncolor)**: Get the single most common color in an image
- **[getImageColors](#getimagecolors)**: Extract representative colors from images using K-Means clustering
- **[getImageDominantColors](#getimagedominantcolors)**: Extract dominant colors by pixel frequency with metadata
- **[textToColor](#texttocolor)**: Generate deterministic colors from strings (*usernames, emails, etc.*)
- **[getSimilarColor](#getsimilarcolor)**: Get random colors in the same palette
- **[random](#random)**: Generate completely random colors
- **[gradient](#gradient)**: Create smooth color gradients between multiple colors

### Using Colority

[](#using-colority)

- **[Ways of using Colority](#ways-of-using-colority)**
    - Helper function `colority()` and facade pattern

### Documentation &amp; Resources

[](#documentation--resources)

- **[API Reference](API.md)**: Complete documentation of all classes and methods
- **[Installation and Requirements](#installation-and-requirements)**: Get started with Composer

**Getting Started**
-------------------

[](#getting-started-1)

### Instantiating Color objects

[](#instantiating-color-objects)

You can convert value colors (*strings or, additionally, depending on the color type, arrays*) to specific `Color` objects.

```
/**
 * RGB format - Commas, whitespace or any combination accepted
 *
 * @var RgbColor $rgbColor
 */
$rgbColor = colority()->fromRgb('rgb(255,255,255)');
$rgbColor = colority()->fromRgb('rgb(255, 255, 255)');
$rgbColor = colority()->fromRgb('rgb(255 255 255)');
$rgbColor = colority()->fromRgb('255,255,255');
$rgbColor = colority()->fromRgb('255 255 255');
$rgbColor = colority()->fromRgb([255, 255, 255]);

/**
 * Hexadecimal format - With or without hash, shorthand supported,
 * and array of three RGB byte values [R, G, B]
 *
 * @var HexColor $hexColor
 */
$hexColor = colority()->fromHex('#51B389');
$hexColor = colority()->fromHex('51B389');
$hexColor = colority()->fromHex('#ABC');
$hexColor = colority()->fromHex([81, 179, 137]);

/**
 * HSL format - Commas, whitespace, with or without deg/% units
 *
 * @var HslColor $hslColor
 */
$hslColor = colority()->fromHsl('hsl(168.31deg, 49.58%, 46.67%)');
$hslColor = colority()->fromHsl('hsl(168.31 49.58% 46.67%)');
$hslColor = colority()->fromHsl('168.31, 49.58, 46.67');
$hslColor = colority()->fromHsl('168.31 49.58 46.67');
$hslColor = colority()->fromHsl([168.31, 49.58, 46.67]);

/**
 * OKLCH format - Commas, whitespace, percentage form for L and C,
 * angle units (deg, rad, turn, grad) for H
 *
 * @var OklchColor $oklchColor
 */
$oklchColor = colority()->fromOklch('oklch(0.70 0.11 163)');
$oklchColor = colority()->fromOklch('oklch(0.70, 0.11, 163)');
$oklchColor = colority()->fromOklch('oklch(70% 27.5% 163deg)');
$oklchColor = colority()->fromOklch('oklch(0.70 0.11 0.45turn)');
$oklchColor = colority()->fromOklch('0.70 0.11 163');
$oklchColor = colority()->fromOklch([0.70, 0.11, 163]);
```

> **Separator flexibility:** RGB, HSL and OKLCH accept commas, whitespace or any combination as component separators (CSS Color Module Level 4). The internal canonical form remains stable: RGB and HSL store with commas, OKLCH stores with whitespace.

If you cannot specify the original format of the value color, use the `parse()` method. It will auto-detect the color type and return the appropriate `Color` object, or `null` if the format is invalid.

```
/** @var RgbColor|null $rgbColor */
$rgbColor = colority()->parse('rgb(255,255,255)');

/** @var HexColor|null $hexColor */
$hexColor = colority()->parse('#51B389');

/** @var HslColor|null $hslColor */
$hslColor = colority()->parse('hsl(168.31deg, 49.58%, 46.67%)');

/** @var OklchColor|null $oklchColor */
$oklchColor = colority()->parse('oklch(0.70 0.11 163)');

/**
 * CSS gradients are auto-detected and resolved to the dominant stop:
 *
 * @var RgbColor|null $dominantColor
 */
$dominantColor = colority()->parse(
    'linear-gradient(135deg, rgb(17, 153, 142) 0%, rgb(56, 239, 125) 100%)'
);

// Always returns null for invalid formats
$invalid = colority()->parse('not-a-color'); // null
```

---

### Gradients

[](#gradients)

`parse()` accepts CSS gradient strings and returns the **dominant single color** of the gradient, the stop whose visual area along the gradient axis is the largest.

```
$color = colority()->parse(
    'linear-gradient(135deg, rgb(17, 153, 142) 0%, rgb(56, 239, 125) 100%)'
);
// rgb(17,153,142) first stop wins on a 50/50 split

$color = colority()->parse(
    'linear-gradient(rgb(255,0,0) 0%, rgb(0,0,255) 30%, rgb(0,255,0) 100%)'
);
// rgb(0,0,255) blue dominates the 15%-65% range (50 units of width)
```

**Supported syntax:**

- `linear-gradient(...)`, `radial-gradient(...)`, `conic-gradient(...)`.
- Any combination of CSS-supported color formats inside the stops (hex, rgb, hsl, oklch).
- Optional `%` after each stop. Missing positions are filled in following CSS rules: first stop defaults to `0%`, last stop defaults to `100%`, intermediate gaps are evenly distributed between declared neighbors.
- Trailing `!important` is stripped before parsing.
- Metadata segments (angle like `135deg`, shape like `circle`, position like `from 90deg at 50% 50%`) are detected and skipped.

**Dominance rule:** for each stop the dominance interval is bounded by the midpoints with its neighbors (clamped to `[0, 100]` at the ends). The stop with the widest interval wins. Ties resolve to the first stop in declaration order.

**Limitations:**

- Named CSS colors (`red`, `blue`, etc.) are not supported as stops; use hex/rgb/hsl/oklch.
- The library returns one of the original stops, not a perceptual average. If every stop fails to parse, `parse()` returns `null`.

---

### Contrast ratio (*WCAG 2.0 standard*)

[](#contrast-ratio-wcag-20-standard)

When you have the `Color` object, you will be able to use all its methods. Below, we describe two of them related to the contrast ratio.

#### getBestForegroundColor

[](#getbestforegroundcolor)

Returns a `Color` object with the most suitable foreground color (*using the Luminosity Contrast Ratio algorithm*).

You can pass an array with `Color` objects as a parameter, so it chooses the foreground color with the best contrast ratio. If no parameter is specified, it will default to white or black.

```
$hexColor = colority()->fromHex('#51B389');

/**
 * Automatic choice: Returns black or white, whichever has better contrast
 *
 * @var HexColor $bestForegroundHexColor
 */
$bestForegroundHexColor = $hexColor->getBestForegroundColor();

/**
 * Custom palette: Chooses the best option from your brand colors
 *
 * @var HexColor $bestForegroundHexColor
 */
$bestForegroundHexColor = $hexColor->getBestForegroundColor([
    new HexColor('#A63F3F'),
    new HexColor('#3FA684'),
    new HexColor('#6E3FA6'),
]);
```

#### getContrastRatio

[](#getcontrastratio)

Returns the contrast ratio (*higher is better contrast, lower is worse*) between the color invoking this method and the color passed as a parameter. If no color is passed as a parameter, the contrast ratio against black as foreground will be determined.

```
$hexColor = colority()->fromHex('#51B389');

/**
 * Contrast ratio with black (default)
 *
 * @var float $contrastRatio
 */
$contrastRatio = $hexColor->getContrastRatio();

/**
 * Contrast ratio with a specific foreground color
 *
 * @var float $contrastRatio
 */
$contrastRatio = $hexColor->getContrastRatio(new HexColor('#3FA684'));
```

**Contrast ratio scale:**

- **1.0**: No contrast (same color)
- **3.0**: Minimum for UI components (WCAG AA)
- **4.5**: Minimum for normal text (WCAG AA)
- **7.0**: Enhanced contrast for normal text (WCAG AAA)
- **21.0**: Maximum contrast (black on white)

#### getMatchingForegroundColor

[](#getmatchingforegroundcolor)

Generates a foreground color that **preserves the background's hue** while meeting WCAG contrast requirements.

> **Difference from `getBestForegroundColor`:**
>
> - `getBestForegroundColor()` picks the best color from a list of candidates (defaults to black/white)
> - `getMatchingForegroundColor()` generates a new color by adjusting lightness while keeping the same hue

```
use Tomloprod\Colority\Support\Algorithms\ContrastRatioScore;

$backgroundColor = colority()->fromHex('#336699');

// AAA level by default
$foregroundColor = $backgroundColor->getMatchingForegroundColor();

// AA level for relaxed contrast requirements
$foregroundColor = $backgroundColor->getMatchingForegroundColor(ContrastRatioScore::Good);

// With custom lightness step (faster but less precise)
$foregroundColor = $backgroundColor->getMatchingForegroundColor(
    targetScore: ContrastRatioScore::Good,
    lightnessStep: 5 // the default value is 1
);
```

**Optional parameters:**

- `targetScore` *(default: ContrastRatioScore::Excellent)*: The desired contrast level. See [ContrastRatioScore Enum](#contrastratioscore-enum).
- `lightnessStep` *(default: 1)*: The amount of lightness points (1-100) to jump in each iteration while searching for a matching color. Larger values are faster but less precise.

#### ContrastRatioScore Enum

[](#contrastratioscore-enum)

The `Tomloprod\Colority\Support\Algorithms\ContrastRatioScore` enum defines the standard contrast levels and provides helper methods to validate them.

**Available contrast levels:**

- `ContrastRatioScore::Excellent` *(default)*: 7:1 ratio (WCAG AAA for normal text)
- `ContrastRatioScore::Good`: 4.5:1 ratio (WCAG AA for normal text)
- `ContrastRatioScore::Acceptable`: 3:1 ratio (WCAG AA for large text/UI).
- `ContrastRatioScore::Insufficient`

You can also use the enum's static methods to manually check if a specific contrast ratio meets WCAG levels:

```
/** @var HexColor $hexColor */
$hexColor = colority()->fromHex('#51B389');

/**
 * The `getContrastRatio` method can take a `Color` object as the foreground
 * to calculate the contrast ratio against that color. Black is used by default.
 *
 * @var float $contrastRatio
 */
$contrastRatio = $hexColor->getContrastRatio();

/**
 * AA Level for texts
 */
$passsesAALevelForLargeText = ContrastRatioScore::passesTextAALevel(
    contrastRatio: $contrastRatio,
    largeText: true
);

$passsesAALevelForNormalText = ContrastRatioScore::passesTextAALevel(
    contrastRatio: $contrastRatio,
    largeText: false
);

/**
 * AAA Level for texts
 */
$passsesAAALevelForLargeText = ContrastRatioScore::passesTextAAALevel(
    contrastRatio: $contrastRatio,
    largeText: true
);

$passsesAAALevelForNormalText = ContrastRatioScore::passesTextAAALevel(
    contrastRatio: $contrastRatio,
    largeText: false
);

/**
 * AA Level for Graphical Objects and User Interface Components
 */
$passsesAALevelForUI = ContrastRatioScore::passesUIAALevel(
    $contrastRatio
);
```

---

### Color validation

[](#color-validation)

The concrete `Color` classes have a static method called `getParser()` which returns an instance of `ValueColorParser`.

The `parse` method returns a string with the value color adapted to work correctly with Colority or throws an `InvalidArgumentException` when it's not valid.

```
use Tomloprod\Colority\Colors\HexColor;
use InvalidArgumentException;

$hexParser = HexColor::getParser();

try {

    // This will throw InvalidArgumentException
    $valueColor = $hexParser->parse('Not a valid value color');

} catch (InvalidArgumentException $e) {
    // Handle invalid color format
}

// Normalize shorthand: Returns "#FFFFFF"
$valueColor = $hexParser->parse('#FFF');
```

You can use the specific parser for any type of color:

```
use Tomloprod\Colority\Colors\{HexColor, HslColor, RgbColor, OklchColor};

$hexParser = HexColor::getParser(); // Validates Hex format
$hslParser = HslColor::getParser(); // Validates HSL format
$rgbParser = RgbColor::getParser(); // Validates RGB format
$oklchParser = OklchColor::getParser(); // Validates OKLCH format
```

### Color conversion

[](#color-conversion)

Colority allows you to convert a Color object to any other `Color` object of the desired format.

```
$hexColor = colority()->fromHex('#51B389');

/** @var HexColor $hexColor */
$hexColor = $hexColor->toHex();

/** @var RgbColor $rgbColor */
$rgbColor = $hexColor->toRgb();

/** @var HslColor $hslColor */
$hslColor = $hexColor->toHsl();

/** @var OklchColor $oklchColor */
$oklchColor = $hexColor->toOklch();
```

**Note:** Conversions between RGB, HSL, and Hex are lossless. Conversions involving OKLCH may be lossy (due to gamut clipping-OKLCH can represent colors outside the sRGB gamut that must be clipped to the nearest displayable color).

#### CSS-ready string with measure units

[](#css-ready-string-with-measure-units)

`HslColor` and `OklchColor` implement the `HasMeasureUnits` interface, which exposes a string with the conventional unit suffixes for the format.

```
$hsl = colority()->fromHsl([180, 50, 50]);
$hsl->getValueColor(); // "hsl(180,50,50)"
$hsl->getValueColorWithMeasureUnits();  // "hsl(180deg,50%,50%)"

$oklch = colority()->fromOklch([0.5, 0.1, 180]);
$oklch->getValueColor(); // "oklch(0.5 0.1 180)"
$oklch->getValueColorWithMeasureUnits();  // "oklch(50% 25% 180deg)"
```

For OKLCH, L is rendered as a percentage of `1`, C as a percentage of the `0.4` reference (so `0.1` becomes `25%`), and H with the `deg` suffix.

---

### Semantic palette

[](#semantic-palette)

Colority ships with eight semantic color slots `primary`, `secondary`, `success`, `danger`, `warning`, `info`, `light`, `dark`, preloaded with default values and overridable per slot, in bulk, or all at once.

```
// Defaults are available out of the box.
colority()->primary(); // HexColor #5B8DEF
colority()->success(); // HexColor #4BD396
colority()->danger(); // HexColor #F5707A
```

#### Override individual slots

[](#override-individual-slots)

Each slot has a dedicated setter. Both `Color` instances and hex strings are accepted.

```
colority()->setPrimary('#FF6347');
colority()->setDanger(colority()->fromOklch('oklch(0.6 0.2 30)'));

colority()->primary()->getValueColor(); // "#FF6347"
```

#### Bulk configuration

[](#bulk-configuration)

`configure()` overrides multiple slots at once and preserves the ones not provided.

```
colority()->configure([
    'primary' => '#FF6347',
    'success' => '#00CED1',
    'warning' => colority()->fromHsl('hsl(40, 90%, 60%)'),
]);
```

#### Custom slot names

[](#custom-slot-names)

Beyond the eight semantic names, you can register and read arbitrary slots through the generic accessors.

```
colority()->setColor('brand', '#0D6EFD');
colority()->setColor('accent', '#FF00AA');

colority()->color('brand');   // ?Color
colority()->color('unknown'); // null
```

#### Reverting to defaults

[](#reverting-to-defaults)

`resetPalette()` discards every override and restores the eight defaults. Useful between tests.

```
colority()->resetPalette();
```

The eight defaults Colority ships with:

SlotHex`primary``#5B8DEF``secondary``#A1A8B3``success``#4BD396``danger``#F5707A``warning``#F9C851``info``#3AC9D6``light``#F4F6F8``dark``#1F2937`#### Build a palette from a brand color

[](#build-a-palette-from-a-brand-color)

`buildPalette()` derives a coherent palette from a single brand color. The algorithm, applied in HSL space:

SlotFormula`primary`the brand color, untouched`secondary``HSL(brand.H + 180°, max(10, brand.S × 0.4), brand.L)`, complementary hue with saturation reduced to 40% (floored at 10 so it never goes pure grey). When the brand itself is near-grey (`S < 5`), the default secondary is used instead.`light``brand.lighter(40)`, lightness + 40 (clamped to 100)`dark``brand.darker(40)`, lightness - 40 (clamped to 0)The semantic slots (`success`, `danger`, `warning`, `info`) keep their library defaults so they remain visually recognizable across brands. Any custom slots previously registered via `setColor()` are dropped, `buildPalette()` rebuilds the whole palette.

```
colority()->buildPalette('#FF6347');

colority()->primary(); // #FF6347 (your brand)
colority()->secondary(); // complementary hue, desaturated
colority()->light(); // brand brightened
colority()->dark(); // brand darkened
```

---

### Color utilities

[](#color-utilities-1)

#### Color Adjustments

[](#color-adjustments)

Adjust the brightness (lightness) and saturation of any color. All methods return an `HslColor` that you can convert as needed.

```
$color = colority()->fromHex('#3498db');

// Adjust brightness
$color->lighter(); // 10% brighter (default)
$color->lighter(20); // 20% brighter
$color->darker(); // 10% darker (default)
$color->darker(15); // 15% darker

// Adjust saturation
$color->saturate(); // 10% more saturated
$color->desaturate(25); // 25% less saturated

// Direct adjustment (positive or negative)
$color->adjustLightness(30); // +30% lightness
$color->adjustSaturation(-20); // -20% saturation

// Convert result to any format
$color->lighter()->toHex(); // Get as HexColor
$color->darker()->toRgb(); // Get as RgbColor
```

#### getImageMostCommonColor

[](#getimagemostcommoncolor)

Returns the single most common color in an image based on pixel frequency.

```
/** @var RgbColor $mostCommon */
$mostCommon = colority()->getImageMostCommonColor(__DIR__.'/photo.png');

echo $mostCommon->toHex()->getValueColor(); // e.g., "#3A7B5C"
```

#### getImageColors

[](#getimagecolors)

It allows you to obtain the colors detected in an image. As the first argument, the path to the image must be provided.

It has an optional second parameter (default is 5) that specifies the number of colors to be returned.

[![getImageColors gif](./docs/example-get-image-colors.gif)](./docs/example-get-image-colors.gif)

```
/** @var array $imageColors */
$imageColors = colority()->getImageColors(
    imagePath: __DIR__.'/image-colors.png',
    desiredNumColors: 10
);
```

#### getImageDominantColors

[](#getimagedominantcolors)

Extracts the most dominant colors based on **pixel frequency**, returning detailed metadata for each color.

```
use Tomloprod\Colority\Support\Dtos\ImageColorFrequency;

/** @var array $dominantColors */
$dominantColors = colority()->getImageDominantColors(
    imagePath: __DIR__.'/photo.png',
    desiredNumColors: 5
);

foreach ($dominantColors as $frequency) {
    $frequency->color; // RgbColor object
    $frequency->percentage; // e.g., 45.2
    $frequency->pixelCount; // e.g., 4520
}
```

**Optional parameter:**

- `similarityThreshold` *(default: 50)*: Minimum RGB distance (0-441) to consider colors as distinct. Higher values filter out more similar colors.

```
// More aggressive filtering (groups similar shades)
$dominantColors = colority()->getImageDominantColors(
    imagePath: __DIR__.'/photo.png',
    desiredNumColors: 5,
    similarityThreshold: 80
);
```

#### textToColor

[](#texttocolor)

Generate a deterministic color based on any string. Same input always produces the same color.

[![getSimilarColor gif](./docs/example-text-to-color.gif)](./docs/example-text-to-color.gif)

```
/**
 * Basic usage - generates a unique color from text
 *
 * @var HslColor $hslColor
 */
$hslColor = colority()->textToColor("Hi, I'm Tomás");
```

**Constrain to a color range:**

Pass a `fromColor` to generate only colors within the same hue range.

```
/**
 * Only grayscale colors will be generated
 *
 * @var HslColor $hslColor
 */
$hslColor = colority()->textToColor(
    "Hi, I'm Tomás",
    colority()->fromHex('#CCC')
);
```

**Interpolate between two colors:**

Pass both `fromColor` and `toColor` to perform **linear interpolation**. The same text always maps to the same position in the gradient.

```
/**
 * Color will fall somewhere between light green and dark teal
 *
 * @var HslColor $hslColor
 */
$hslColor = colority()->textToColor(
    "Hi, I'm Tomás",
    colority()->fromHex('#85d5a4'), // Start: Light green
    colority()->fromHex('#165a59')  // End: Dark teal
);
```

#### getSimilarColor

[](#getsimilarcolor)

Generate a random color similar to a given color (*within the same color palette*).

[![getSimilarColor gif](./docs/example-get-similar-color.gif)](./docs/example-get-similar-color.gif)

```
$hexColor = colority()->fromHex('#51B389');

/**
 * Get a random similar color (default variation ranges)
 *
 * @var HexColor $similarHexColor
 */
$similarHexColor = colority()->getSimilarColor($hexColor);

// Fine-tune the similarity with custom ranges
$similarHexColor = colority()->getSimilarColor(
    $hexColor,
    hueRange: 20, // +- 20 degrees on color wheel
    saturationRange: 5, // +- 5% saturation
    lightnessRange: 5 // +- 5% lightness
);
```

#### random

[](#random)

Generates a completely random color.

```
/**
 * Returns a random HSL color
 *
 * @var HslColor $randomColor
 */
$randomColor = colority()->random();

// And, if you want, convert to your preferred format
$hexRandom = $randomColor->toHex();
```

#### gradient

[](#gradient)

Generates a smooth gradient of colors between multiple color stops.

```
/**
 * Create a 10-step gradient from red -> green -> blue
 *
 * @var array $gradient
 */
$gradient = colority()->gradient(
    colors: [
        colority()->fromHex('#ff0000'), // Red
        colority()->fromHex('#00ff00'), // Green
        colority()->fromHex('#0000ff') // Blue
    ],
    steps: 10
);
```

This returns an array of 10 `HexColor` objects.

---

### Ways of using Colority

[](#ways-of-using-colority)

You can use Colority either with the helper function `colority()`:

```
use Tomloprod\Colority\Colors\HexColor;

/**
 * Using the helper function
 *
 * @var HexColor $hexColor
 */
$hexColor = colority()->fromHex('#CCC');
```

or by directly invoking the static methods of the `Colority` facade:

```
use Tomloprod\Colority\Support\Facades\Colority;
use Tomloprod\Colority\Colors\HexColor;

/**
 * Using the facade directly
 *
 * @var HexColor $hexColor
 */
$hexColor = Colority::fromHex('#CCC');
```

Both approaches are equivalent.

**API Reference**
-----------------

[](#api-reference)

Colority provides a comprehensive API through its facade and color classes.

**[View complete API documentation](API.md)**

**Installation and Requirements**
---------------------------------

[](#installation-and-requirements)

#### **Requires [PHP 8.2+](https://php.net/releases/)**

[](#requires-php-82)

You may use [Composer](https://getcomposer.org) to install Colority into your PHP project:

```
composer require tomloprod/colority
```

**Upgrade from 1.x to 2.0**
---------------------------

[](#upgrade-from-1x-to-20)

Most consumers (those using `colority()` or the `Colority` facade) do not need to change anything. The breaking changes affect only callers who reach into the internal parser API:

- `Tomloprod\Colority\Contracts\ValueColorParser::parse()` now returns `array` instead of `string`. Direct callers must adapt to the new return shape.
- `ColorityManager::fromHex()` and `Colority::fromHex()` accept `string|array`. Existing string usage is unchanged; the array form is additive.
- `colority()->parse()` now intercepts CSS gradient strings and returns the dominant stop color. Code that relied on `parse()` returning `null` for gradients should use the `GradientResolver::isGradient()` static check.
- `getMatchingForegroundColor()` defaults `targetScore` to `ContrastRatioScore::Excellent` (7:1, WCAG AAA) instead of `ContrastRatioScore::Good` (4.5:1, WCAG AA). Pass the enum explicitly to opt back into the previous default.

**Contributing**
----------------

[](#contributing)

Contributions are welcome, and are accepted via pull requests. Please [review these guidelines](./CONTRIBUTING.md) before submitting any pull requests.

---

**Colority** was created by **[Tomás López](https://twitter.com/tomloprod)** and open-sourced under the **[MIT license](https://opensource.org/licenses/MIT)**.

###  Health Score

58

—

FairBetter than 98% of packages

Maintenance89

Actively maintained with recent releases

Popularity52

Moderate usage in the ecosystem

Community17

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 97.6% 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

Every ~89 days

Recently: every ~39 days

Total

9

Last Release

55d ago

Major Versions

v1.7.0 → v2.0.02026-05-09

### Community

Maintainers

![](https://www.gravatar.com/avatar/1c9df012919bdcf3f17fad0e3a84ec77641f1f9671f85cb9c4377242ba09dde8?d=identicon)[tomloprod](/maintainers/tomloprod)

---

Top Contributors

[![tomloprod](https://avatars.githubusercontent.com/u/7898894?v=4)](https://github.com/tomloprod "tomloprod (40 commits)")[![smncd](https://avatars.githubusercontent.com/u/56580659?v=4)](https://github.com/smncd "smncd (1 commits)")

---

Tags

accessibilityavatar-generatorcolor-conversioncolor-librarycolor-manipulationcolorscontrast-ratiofluent-apigradientimage-processingpalettephpphp8wcagutilitycolorsconversion-utiliywcag-contrast

###  Code Quality

TestsPest

Static AnalysisRector

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/tomloprod-colority/health.svg)

```
[![Health](https://phpackages.com/badges/tomloprod-colority/health.svg)](https://phpackages.com/packages/tomloprod-colority)
```

###  Alternatives

[nette/utils

🛠 Nette Utils: lightweight utilities for string &amp; array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.

2.1k430.4M1.7k](/packages/nette-utils)[danielstjules/stringy

A string manipulation library with multibyte support

2.4k26.3M192](/packages/danielstjules-stringy)[voku/arrayy

Array manipulation library for PHP, called Arrayy!

4915.7M18](/packages/voku-arrayy)[mage2tv/magento-cache-clean

This package has been migrated to mage-os/magento-cache-clean. Please switch over at your convenience.

5442.1M3](/packages/mage2tv-magento-cache-clean)[vaimo/composer-patches

Applies a patch from a local or remote file to any package that is part of a given composer project. Patches can be defined both on project and on package level. Optional support for patch versioning, sequencing, custom patch applier configuration and patch command for testing/troubleshooting added patches.

3014.6M26](/packages/vaimo-composer-patches)[lodash-php/lodash-php

A port of Lodash to PHP

528756.5k5](/packages/lodash-php-lodash-php)

PHPackages © 2026

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