Converting between formats
Each color class provides to* methods for the formats it can convert to. The
methods return new instances of the target class.
Conversion matrix
| From \ To | Hex | RGB | HSL | HSV |
|---|---|---|---|---|
| Hex | — | yes | yes | yes |
| RGB | yes | — | yes | yes |
| HSL | yes | yes | — | via RGB |
| HSV | yes | yes | via RGB | — |
| RAL | yes | yes | yes | yes |
| Named | yes | yes | yes | yes |
HSLColor and HSVColor do not expose direct toHSV() / toHSL() methods.
Convert through RGB when moving between the two hue-based formats:
$hsv = HSLColor::create([180, 0.5, 0.7])->toRGB()->toHSV();
NamedColor converts to any format through its hex value, just like RALColor:
use Renfordt\Colors\NamedColor;
$hex = NamedColor::create('rebeccapurple')->toHex(); // #663399
$hsl = NamedColor::create('rebeccapurple')->toHSL(); // HSLColor
Examples
use Renfordt\Colors\{HexColor, RGBColor};
$hex = HexColor::create('#FF5733');
$rgb = $hex->toRGB(); // RGBColor
$hsl = $hex->toHSL(); // HSLColor
$hsv = $hex->toHSV(); // HSVColor
$rgb = RGBColor::create([255, 87, 51]);
$hex = $rgb->toHex(); // HexColor
$hsl = $rgb->toHSL(); // HSLColor
$hsv = $rgb->toHSV(); // HSVColor
Chaining
Because each conversion returns a new instance, conversions chain directly:
$result = HexColor::create('#FF5733')
->toRGB()
->toHSL()
->toHex();
Precision
toHSL() and toHSV() on RGBColor and HexColor accept an optional
$precision argument controlling the rounding of the saturation and
lightness/value components. The default is 4.
$hsl = RGBColor::create([255, 87, 51])->toHSL(precision: 2);
The hue is always rounded to the nearest integer regardless of precision.
Alpha is preserved
Conversions between Hex, RGB, HSL, and HSV carry the alpha (opacity) channel
through, translating between the int (0–255) and float (0.0–1.0)
representations automatically:
RGBColor::create([255, 0, 0, 128])->toHex()->getHexStr(); // #ff000080
HexColor::create('#FF000080')->toRGB()->getRGBA(); // [255, 0, 0, 128]
HSLColor::create([0, 1.0, 0.5, 0.5])->toRGB()->alpha; // 128
When converting to HSL/HSV, the alpha float is rounded using the same
$precision argument as saturation and lightness/value. A fully opaque color is
rendered by HexColor without alpha digits (#FF0000 rather than #FF0000FF).
RALColor and NamedColor have no alpha of their own, so colors converted from
them start fully opaque.