ColorUtil
Raxos\Foundation\Util\ColorUtil is a final class of static helper methods for converting and blending colors between hex, RGB, RGBA, HSL and integer representations.
See the Util classes concept page for an overview of all utility classes.
Signature
namespace Raxos\Foundation\Util;
final class ColorUtilConversion
public static function hexToRgb(string $hex): arrayConverts a hex color string to an [r, g, b] array.
public static function hexToRgba(string $hex): arrayConverts a hex color string to an [r, g, b, a] array.
public static function rgbToHex(int $r, int $g, int $b, bool $includeHashtag = false): stringConverts RGB values to a hex string.
public static function rgbaToHex(int $r, int $g, int $b, float $a, bool $includeHashtag = false): stringConverts RGBA values to a hex string.
public static function rgbToHsl(int $r, int $g, int $b): arrayConverts RGB values to an [h, s, l] array.
public static function hslToRgb(float $h, float $s, float $l): arrayConverts HSL values to an [r, g, b] array.
public static function rgbToInt(int $r, int $g, int $b): int
public static function intToRgb(int $color): array
public static function intToRgba(int $color): arrayConvert between RGB and packed integer representations.
Blending and contrast
public static function blend(array $color1, array $color2, int $weight = 0): arrayBlends two RGBA colors together by the given weight.
public static function shade(array $color, int $weight = 0): arrayBlends the color with black by the given weight.
public static function tint(array $color, int $weight = 0): arrayBlends the color with white by the given weight.
public static function luminance(int $r, int $g, int $b): floatCalculates the relative luminance of an RGB color.
public static function yiq(int $r, int $g, int $b): floatCalculates the YIQ value of an RGB color.
public static function lightOrDark(array $color, array $dark = [0, 0, 0], array $light = [255, 255, 255], float $delta = 0.5): arrayReturns a light or dark contrasting color depending on the luminance of the input color.
Example
<?php
declare(strict_types=1);
use Raxos\Foundation\Util\ColorUtil;
$rgb = ColorUtil::hexToRgb('#3366ff'); // [51, 102, 255]
$hex = ColorUtil::rgbToHex(51, 102, 255, includeHashtag: true); // '#3366ff'
$contrast = ColorUtil::lightOrDark([51, 102, 255]);