function Color::hexToRgb

Same name in other branches
  1. 9 core/lib/Drupal/Component/Utility/Color.php \Drupal\Component\Utility\Color::hexToRgb()
  2. 8.9.x core/lib/Drupal/Component/Utility/Color.php \Drupal\Component\Utility\Color::hexToRgb()
  3. 11.x core/lib/Drupal/Component/Utility/Color.php \Drupal\Component\Utility\Color::hexToRgb()

Parses a hexadecimal color string like '#abc' or '#aabbcc'.

Parameters

string $hex: The hexadecimal color string to parse.

Return value

array An array containing the values for 'red', 'green', 'blue'.

Throws

\InvalidArgumentException

4 calls to Color::hexToRgb()
Color::validateColor in core/lib/Drupal/Core/Render/Element/Color.php
Form element validation handler for #type 'color'.
ColorTest::testHexToRgb in core/tests/Drupal/Tests/Component/Utility/ColorTest.php
Tests Color::hexToRgb().
CreateNew::execute in core/modules/system/src/Plugin/ImageToolkit/Operation/gd/CreateNew.php
Performs the actual manipulation on the image.
Rotate::validateArguments in core/modules/system/src/Plugin/ImageToolkit/Operation/gd/Rotate.php
Validates the arguments.

File

core/lib/Drupal/Component/Utility/Color.php, line 38

Class

Color
Performs color conversions.

Namespace

Drupal\Component\Utility

Code

public static function hexToRgb($hex) {
    if (!self::validateHex($hex)) {
        throw new \InvalidArgumentException("'{$hex}' is not a valid hex value.");
    }
    // Ignore '#' prefixes.
    $hex = ltrim($hex, '#');
    // Convert shorthands like '#abc' to '#aabbcc'.
    if (strlen($hex) == 3) {
        $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
    }
    $c = hexdec($hex);
    return [
        'red' => $c >> 16 & 0xff,
        'green' => $c >> 8 & 0xff,
        'blue' => $c & 0xff,
    ];
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.