Skip to main content

Named colors

NamedColor represents a color from the standard set of CSS/X11 color names, such as red, rebeccapurple, or dodgerblue. A single name→hex table backs the class, and every other representation is derived from it through the normal conversion chain.

Creating a named color

use Renfordt\Colors\NamedColor;

$named = NamedColor::create('RebeccaPurple'); // case-insensitive
echo $named->name; // rebeccapurple

Names are normalized (trimmed and lower-cased) and validated. An unknown name raises InvalidArgumentException:

NamedColor::create('notacolor'); // throws InvalidArgumentException

To check first without catching an exception, use exists():

if (NamedColor::exists('tomato')) {
$named = NamedColor::create('tomato');
}

Converting from a named color

Named colors convert to hex through the lookup table, and to other formats through hex:

$named = NamedColor::create('rebeccapurple');

$hex = $named->toHex(); // #663399
$rgb = $named->toRGB(); // RGBColor
$hsl = $named->toHSL(); // HSLColor
$hsv = $named->toHSV(); // HSVColor

Finding the name of a color

You can look a color up by its value. fromHex() and fromRGB() return the exact matching NamedColor, or null when no standard color shares that value:

use Renfordt\Colors\{HexColor, RGBColor, NamedColor};

NamedColor::fromHex(HexColor::create('#ff6347')); // NamedColor "tomato"
NamedColor::fromRGB(RGBColor::create([255, 99, 71])); // NamedColor "tomato"
NamedColor::fromRGB(RGBColor::create([1, 2, 3])); // null

RGBColor and HexColor expose the same exact lookup as getName():

RGBColor::create([255, 99, 71])->getName(); // "tomato"
HexColor::create('#ff6347')->getName(); // "tomato"
HexColor::create('#010203')->getName(); // null

The match is on the RGB components only — alpha is ignored.

Finding the closest name

When there is no exact match, findClosest() returns the standard color nearest to the given color, measured as the Euclidean distance in RGB space. It accepts a HexColor or an RGBColor and always returns a NamedColor:

$nearest = NamedColor::findClosest(HexColor::create('#ff6300'));
echo $nearest->name; // nearest standard color, e.g. "orangered"

Listing all names

all() returns the complete name => hex map:

foreach (NamedColor::all() as $name => $hex) {
// ...
}