Naming an arbitrary colour means finding the nearest entry in the web colour table. The library implements two distance measures, and they select a different name for close to half of the RGB cube.
The Two Answers
<?php
require_once __DIR__ . '/vendor/autoload.php';
$web = new \Com\Tecnick\Color\Web();
echo $web->getClosestWebColorFromString('#9577a6'), "\n";
echo $web->getClosestWebColorByDeltaEFromString('#9577a6'), "\n";
lightslategray
plum
Euclidean distance in sRGB places #9577a6 next to lightslategray; CIE76 distance in CIE Lab places it next to plum.
| Swatch | Name | |
|---|---|---|
| Input | #9577a6 | |
| sRGB | lightslategray | |
| CIE76 | plum |
sRGB distance weights the three channels equally, which does not track perceived difference. Lab distance costs one conversion more and is perceptually uniform to within the limits of CIE76. Use the Lab form unless the target set was itself defined by RGB proximity.
Over 4096 evenly spaced RGB colours the two methods pick a different name for 1916 of them, 46.8 percent. On the 150 table entries themselves both are exact, returning the colour’s own name for 139 of the 150; the other 11 are the alias names, which resolve to whichever spelling comes first.
The Arrays
Four methods take a colour string and convert it themselves. Two take a component array, and the two arrays are not the same shape.
| Method | Takes |
|---|---|
getClosestWebColorFromString() | a colour string |
getClosestWebColorByDeltaEFromString() | a colour string |
getClosestWebColor() | an RGB array, from toRgbArray() |
getClosestWebColorByDeltaE() | a Lab array, from toLabArray() |
getRgbSquareDistance() | two RGB arrays |
getLabSquareDistance() | two Lab arrays |
Passing an RGB array to the Lab method does not raise. The lstar, astar and bstar keys are absent, each reads as 0.0, and every colour resolves near black:
$col = $web->getColorObj('#9577a6');
// getClosestWebColor takes RGB, getClosestWebColorByDeltaE takes Lab
echo $web->getClosestWebColor($col->toRgbArray()), "\n";
echo $web->getClosestWebColorByDeltaE($col->toLabArray()), "\n";
// an RGB array read as Lab: the missing keys default to 0.0
echo $web->getClosestWebColorByDeltaE($col->toRgbArray()), "\n";
lightslategray
plum
black
The string forms build the correct array themselves. Use them unless a model object is already in hand.
Inverting And Naming
$col = $web->getColorObj('#336699');
echo $web->getClosestWebColor($col->toRgbArray()), "\n";
echo $web->getClosestWebColor($col->withInvertedColor()->toRgbArray()), "\n";
steelblue
darkkhaki
Both distance functions return the square of the distance. That orders correctly, which is all the lookups need, and it is not the distance itself.
See Also
- tc-lib-color : the library overview.
- Web Colours : the table being searched.
- CIE Lab : the space CIE76 measures in.
- Conversions :
toRgbArray()andtoLabArray(). - API reference : the generated class documentation.