Skip to main content

RGBColor

Renfordt\Colors\RGBColor

Represents a color as red, green, and blue components in the range 0–255. RGB is the format most conversions route through.

Properties

PropertyTypeRangeNotes
redint0–255Clamped on assignment
greenint0–255Clamped on assignment
blueint0–255Clamped on assignment
alphaint0–255Opacity; 255 = opaque. Defaults to 255. Clamped on assignment

Static methods

create(array $rgb): RGBColor

Creates an instance from [red, green, blue], with an optional 4th alpha element ([red, green, blue, alpha]). Alpha defaults to 255 (opaque) when omitted.

$rgb = RGBColor::create([255, 87, 51]);
$rgba = RGBColor::create([255, 87, 51, 128]); // 50% opaque

make(array $rgb): RGBColor

Alias of create().

Instance methods

getRGB(): array

Returns the components as [red, green, blue] (alpha excluded).

getRGBA(): array

Returns the components as [red, green, blue, alpha].

getName(): ?string

Returns the standard color name that matches this color exactly, or null when no standard color matches. The match is on the RGB components only; alpha is ignored. See NamedColor.

RGBColor::create([255, 99, 71])->getName(); // "tomato"
RGBColor::create([1, 2, 3])->getName(); // null

toHex(): HexColor

Converts to a HexColor. When alpha is below 255 the result is an 8-digit #RRGGBBAA string; a fully opaque color produces a plain 6-digit string.

toHSL(int $precision = 4): HSLColor

Converts to HSLColor. $precision controls rounding of saturation, lightness, and alpha. Hue is rounded to an integer. Alpha is converted to a 0.01.0 float.

toHSV(int $precision = 4): HSVColor

Converts to HSVColor. $precision controls rounding of saturation, value, and alpha. Hue is rounded to an integer. Alpha is converted to a 0.01.0 float.

Example

$rgb = RGBColor::create([255, 100, 50]);
$rgb->green = 300; // clamped to 255

[$r, $g, $b] = $rgb->getRGB();
$hex = $rgb->toHex();
$hsl = $rgb->toHSL(precision: 2);