You are here

public function ColorapiService::hexToRgb in Color API 8

Helper function to convert hex to rgb.

Parameters

string $hex: The color in hexadecimal string format.

string $colorIndex: The color value to return, must be one of:

  • red
  • green
  • blue.

Overrides ColorapiServiceInterface::hexToRgb

File

src/Service/ColorapiService.php, line 22

Class

ColorapiService
Service class for the Color API module.

Namespace

Drupal\colorapi\Service

Code

public function hexToRgb($hex, $colorIndex) {
  $hex = str_replace("#", "", $hex);
  if ($colorIndex == 'red') {
    if (strlen($hex) == 3) {
      $rgb_value = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
    }
    else {
      $rgb_value = hexdec(substr($hex, 0, 2));
    }
  }
  elseif ($colorIndex == 'green') {
    if (strlen($hex) == 3) {
      $rgb_value = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
    }
    else {
      $rgb_value = hexdec(substr($hex, 2, 2));
    }
  }
  if ($colorIndex == 'blue') {
    if (strlen($hex) == 3) {
      $rgb_value = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
    }
    else {
      $rgb_value = hexdec(substr($hex, 4, 2));
    }
  }
  return $rgb_value;
}