function Color::rgbToHex

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

Converts RGB color arrays or strings to lowercase CSS notation.

Parameters

array|string $input: The value to convert. If the value is an array the first three elements will be used as the red, green and blue components. String values in CSS notation like '10, 20, 30' are also supported.

Return value

string The lowercase simple color representation of the given color.

3 calls to Color::rgbToHex()
Color::validateColor in core/lib/Drupal/Core/Render/Element/Color.php
Form element validation handler for #type 'color'.
ColorTest::testRgbToHex in core/tests/Drupal/Tests/Component/Utility/ColorTest.php
Tests Color::rgbToHex().
GDToolkit::getTransparentColor in core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php
Gets the color set for transparency in GIF images.

File

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

Class

Color
Performs color conversions.

Namespace

Drupal\Component\Utility

Code

public static function rgbToHex($input) {
    // Remove named array keys if input comes from Color::hex2rgb().
    if (is_array($input)) {
        $rgb = array_values($input);
    }
    elseif (is_string($input)) {
        preg_match('/(\\d+), ?(\\d+), ?(\\d+)/', $input, $rgb);
        array_shift($rgb);
    }
    $out = 0;
    foreach ($rgb as $k => $v) {
        $out |= $v << 16 - $k * 8;
    }
    return '#' . str_pad(dechex($out), 6, '0', STR_PAD_LEFT);
}

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