PHPackages                             savvywombat/color - 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. savvywombat/color

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

savvywombat/color
=================

Package for manipulating colors in multiple color spaces.

1.3.1(3y ago)513.8k↓27.8%2[2 PRs](https://github.com/SavvyWombat/color-php/pulls)MITPHPPHP ^7.4||^8

Since Jul 23Pushed 1y agoCompare

[ Source](https://github.com/SavvyWombat/color-php)[ Packagist](https://packagist.org/packages/savvywombat/color)[ Docs](https://github.com/SavvyWombat/color-php)[ RSS](/packages/savvywombat-color/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (2)Versions (6)Used By (0)

SavvyWombat Color
=================

[](#savvywombat-color)

[![Latest Version on Packagist](https://camo.githubusercontent.com/2603fb2f9fdf9f275613258fe3f83297385e9df4b6a35ec9a2ba8c99c47dbd4e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7361767679776f6d6261742f636f6c6f722e737667)](https://packagist.org/packages/savvywombat/color)[![Supported PHP Version](https://camo.githubusercontent.com/108ed5acbefd0bb121879b82738c43e73ccf73648b0735e6139c94bb044b43d4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f7361767679776f6d6261742f636f6c6f723f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/108ed5acbefd0bb121879b82738c43e73ccf73648b0735e6139c94bb044b43d4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f7361767679776f6d6261742f636f6c6f723f7374796c653d666c61742d737175617265)[![Software License](https://camo.githubusercontent.com/074b89bca64d3edc93a1db6c7e3b1636b874540ba91d66367c0e5e354c56d0ea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e737667)](LICENSE.md)[![Build](https://camo.githubusercontent.com/6a2b192a108f31190a7fe9517ef822b05beacb3ffc6938e97d42e3d834681638/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f5361767679576f6d6261742f636f6c6f722d7068702f546573743f6c6162656c3d6275696c64)](https://github.com/SavvyWombat/color-php/actions)[![Code Coverage](https://camo.githubusercontent.com/b9fbcf6588b8bd29fba4ce5cc89f75a9577d04405de5b8f400ad8a5f5ff50d14/68747470733a2f2f636f6465636f762e696f2f67682f5361767679576f6d6261742f636f6c6f722d7068702f6272616e63682f6d61696e2f67726170682f62616467652e737667)](https://codecov.io/gh/SavvyWombat/color-php)

A PHP package to help convert between and manipulate HSL and RGB colorspaces/types.

Main features:

- support for CSS Color Module Level 3 color specifications ( #323C46, rgb(50,60,70), hsl(210,16.7%,23.5%) );
- support for alpha transparency ( #323C4680, rgba(50,60,70,0.5), hsla(210,16.7%,23.5%,0.5) );
- modifiers to change red/green/blue or hue/saturation/lightness and alpha on any color type;
- able to extend with custom colorspaces/types which can then be converted and/or modified;
- able to extend with custom modifiers;
- immutable behaviour.

```
$rgb = new \SavvyWombat\Color\RGB(50, 60, 70);
echo (string) $rgb; // rgb(50,60,70)

$hsl = $rgb->toHsl();
echo (string) $hsl; // hsl(210,16.7%,23.5%);

$redderHsl = $hsl->red('+50');
echo (string) $redderHsl; // hsl(345,25%,31.4%);

$lighterRgb = $rgb->lighten('+10%');
echo (string) $lighterRgb; // rgb(55,66,77);

$transparentRgb = $rgb->alpha('0.5');
echo (string) $transparentRgb; // rgb(50,60,70,0.5)

echo (string) $rgb->toHex(); // #323C46
```

Installation
============

[](#installation)

```
composer require savvywombat\color

```

Usage
=====

[](#usage)

Creating a color
----------------

[](#creating-a-color)

The following patterns are available by default to create a color:

```
Color::fromString('#123'); // Hex: #112233
Color::fromString('#1234'); // Hex (with alpha): #11223344
Color::fromString('#123456'); // Hex: #123456
Color::fromString('#12345678'); // Hex: #12345678

Color::fromString('rgb(10, 20, 30)'); // RGB
Color::fromString('rgba(10, 20, 30, 0.4)'); // RGB

Color::fromString('hsl(10, 20%, 30%)'); // HSL
Color::fromString('hsl(10, 20%, 30%, 0.4)'); // HSL
```

Converting a color
------------------

[](#converting-a-color)

Colors can be converted to any other registered color type:

```
echo (string) Color::fromString('#123')->toHsl(); // hsl(210,50%,8.6%)
echo (string) Color::fromString('#123')->toRGB(); // rgb(17,34,51)

echo (string) Color::fromString('rgb(25, 75, 125)')->toHex(); // #194B7D
echo (string) Color::fromString('rgb(25, 75, 125)')->toHsl(); // hsl(210,66.7%,39.4%)

echo (string) Color::fromString('hsl(135, 50%, 75%)')->toHex(); // #9FDFAF
echo (string) Color::fromString('hsl(135, 50%, 75%)')->toRGB(); // rgb(159,223,175)
```

Modifying a color
-----------------

[](#modifying-a-color)

The following methods are available on any registered color type by default:

- `red($value)`
- `green($value)`
- `blue($value)`
- `alpha($value)`
- `hue($value)`
- `saturation($value)`
- `lightness($value)`

All methods return a modified copy of the original object, leaving the original unmodified, and will accept the following argument formats:

```
$newHsl = $hsl->red(50); // set to specific value
$newHsl = $hsl->red('+50'); // add 50 to the current value
$newHsl = $hsl->red('-50'); // remove 50 from the current value
$newHsl = $hsl->red('+50%'); // increase the current value by 50%
$newHsl = $hsl->red('-50%'); // decrease the current value by 50%
$newHsl = $hsl->red('+1/2'); // set to a value halfway between the current value and 255 (maximum red value)
$newHsl = $hsl->red('-1/2'); // set to a value halfway between the current value and 0 (minimum red value)
```

Red, green, blue values are clamped in the range of 0..255. This means that adding 100 to a color which already has a red value of 200 will return a color with red set to 255.

Similarly, saturation and lightness are clamped in the range 0..100, while alpha is clamped between 0 and 1.

Hue is not clamped, as it is possible to rotate more than 360 in either direction (and 420° is equivalent to 60°). Because of this, the fractional pattern ('+1/2') should not be used as there is no minimum or maximum.

Extending
=========

[](#extending)

Custom color types
------------------

[](#custom-color-types)

The package allows you to create your own color types. These must extend `Color`, and implement the following methods from the `ColorInterface`:

```
    public static function fromString(string $colorSpec): ColorInterface;
    public function __toString(): string;

    public static function fromRGB(Rgb $rgb): ColorInterface;
    public function toRGB(): Rgb;
```

#### Registering color types

[](#registering-color-types)

You will need to register the class to allow conversion to and from your new color:

```
Color::registerColor('Gray', Gray::class);
echo (string) Color::fromString('#163248')->toGray(); // #323232
```

You can replace existing color types with new ones.

You can get a list of registered color types via `Color::registeredColors()`.

### `public static function fromString(string $colorSpec): ColorInterface`

[](#public-static-function-fromstringstring-colorspec-colorinterface)

```
echo (string) Color::fromString('#204060')->toGray(); // gray(25%)
echo (string) Color::fromString('gray(50%, 0.25)')->toRGB(); // #80808040
```

The `fromString` accepts a color specification and tests it against the registered patterns and extracts the information.

```
/**
 * color spec pattern: 'gray\((\d{1,3}(\.\d{1})?)%\)'
 * color spec pattern: 'gray\((\d{1,3}(\.\d{1})?)%,([0-1](\.\d{1,2})?)\)'
 *
 * If the color spec matches either of the patterns, extractChannels will return the parameters from the string using regex.
 */
public static function fromString(string $colorSpec): ColorInterface
{
    $channels = Color::extractChannels($colorSpec, self::class);

    if (!isset($channels[3])) {
        $channels[3] = 1.0;
    }

    return new Gray((float) $channels[1], $channels[3]);
}
```

#### Registering color specification patterns

[](#registering-color-specification-patterns)

To register a color specification pattern you must first register the color type it will apply to:

```
Color::registerColor('Gray', Gray::class);
Color::registerColorSpec('gray\((\d{1,3})\)', Gray::class);
```

You register new specifications for any registered color type, including the default types. You can also override registered patterns so that they apply to different color types.

You can get a list of registered color specification via `Color::registeredColorSpecs()`.

### `public function __toString(): string;`

[](#public-function-__tostring-string)

```
public function __toString(): string
{
    $value = round($this->value, 1);
    $alpha = round($this->alpha, 2);

    if ($alpha === 1.0) {
        return "gray({$value},{$alpha})";
    }

    return "gray({$value})";
}
```

### `public static function fromRGB(Rgb $rgb): ColorInterface`

[](#public-static-function-fromrgbrgb-rgb-colorinterface)

This method is used to allow conversion from one color type to any another that has been registered. This means that you only have to specify how to convert *to* your new type *from* an RGB color.

```
public static function fromRGB(Rgb $rgb): ColorInterface
{
    $average = ($rgb->red + $rgb->green + $rgb->blue) / 3;
    $gray = $average * 100 / 255;

    return new Gray($gray, $rgb->alpha);
}
```

### `public function toRGB(): Rgb`

[](#public-function-torgb-rgb)

The abstract `\SavvyWombat\Color\Color` already implements this method:

```
public function toRGB(): Rgb
{
    return new Rgb($this->red, $this->green, $this->blue, $this->alpha);
}
```

The red, green, blue and alpha properties are also defined on the abstract. You can either reimplement the method, or set these values in your color type constructor to make use of the default implementation:

```
use \SavvyWombat\Color\Color;

class Gray extends Color
{
    // gray value in range 0..100
    protected $value;

    public function __construct(float $value, float $alpha = 1.0)
    {
        $this->value = $value;
        $this->alpha = $alpha;

        // calculate RGB equivalent values for easy conversion
        $this->red = $value * 2.55; // convert to 0..255 for RGB
        $this->green = $value * 2.55;
        $this->blue = $value * 2.55;
    }
}
```

It is recommended that you use the default implementation, as the red, green and blue properties are exposed in the public interface.

Custom color modifiers
----------------------

[](#custom-color-modifiers)

Color modifiers are methods on color types that are registered and made available to all other color types.

Calling a modifier on a color type will convert it to the type that implements the registered method, and then convert the result back to the original type. To help with this implicit conversion, custom modifiers must return an object which extends `Color` - ideally, it should be a copy of the same type the method is implemented on.

```
public function gray($gray): self
{
    $gray = $this->adjustValue($this->gray, $gray, 100);

    if ($gray < 0) {
        $gray = 0;
    }

    if ($gray > 100) {
        $gray = 100;
    }

    return new self($gray, $this->alpha);
}
```

`Color::adjustValue($originalValue, $newValue, $max = 0, $min = 0)` handles the various relative arguments (±50 or ±50%) to produce the new calculated value for the property being modified.

The modifier is also responsible for ensuring the new value is valid for the property being modified.

Support for color keywords
--------------------------

[](#support-for-color-keywords)

`Color::fromString()` and `Hex::fromString()` will accept any of the CSS color keywords to create a Hex color.

If you wish to generate a color of a different type from a keyword, you can convert from the Hex color after creation:

```
$hsl = Color::fromString('deepskyblue')->toHsl();
```

License
=======

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance27

Infrequent updates — may be unmaintained

Popularity32

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 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

Every ~199 days

Total

5

Last Release

1328d ago

PHP version history (3 changes)1.0PHP ^7.2

1.2.0PHP ^7.4

1.3.0PHP ^7.4||^8

### Community

Maintainers

![](https://www.gravatar.com/avatar/949f4b63b47c6f037d6ddd22ad3c34e67950655eb51a31d2b1f1205eac7005d7?d=identicon)[SavvyWombat](/maintainers/SavvyWombat)

---

Top Contributors

[![horuskol](https://avatars.githubusercontent.com/u/290549?v=4)](https://github.com/horuskol "horuskol (61 commits)")

---

Tags

convertmanipulationconversioncolorrgbhextransformcolorshslsavvywombatsavvy wombatcolor space

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/savvywombat-color/health.svg)

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

###  Alternatives

[ssnepenthe/color-utils

A PHP library for performing SASS-like color manipulations.

631.1M10](/packages/ssnepenthe-color-utils)[ozdemirburak/iris

PHP library for color manipulation and conversion.

1201.7M16](/packages/ozdemirburak-iris)[spatie/color

A little library to handle color conversions

38118.9M28](/packages/spatie-color)[tecnickcom/tc-lib-color

PHP library to manipulate various color representations

247.2M9](/packages/tecnickcom-tc-lib-color)[fjw/color-compare

A library for converting colors (Hex, RGB, HSL, CIELAB (LAB), DIN-99) and calculating color distances based on DIN-99.

1310.0k](/packages/fjw-color-compare)[syholloway/mrcolor

Color manipulation tools and format conversion for PHP

14149.6k](/packages/syholloway-mrcolor)

PHPackages © 2026

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