Creates color from either short hand like #ff0 or long hex values like #001122
with or without leading hash
@param string $hex The alpha rgb color hex value
@return ArgbColor returns an instance with the defined colors
4584
static function FromRgbHex($hex)
    {
        $cleanHex = ltrim($hex, '#');
        if (strlen($cleanHex) == 3) {
            $r = hexdec(substr($cleanHex, 0, 1) . substr($cleanHex, 0, 1));
            $g = hexdec(substr($cleanHex, 1, 1) . substr($cleanHex, 1, 1));
            $b = hexdec(substr($cleanHex, 2, 1) . substr($cleanHex, 2, 1));
        }
        else {
            $r = hexdec(substr($cleanHex, 0, 2));
            $g = hexdec(substr($cleanHex, 2, 2));
            $b = hexdec(substr($cleanHex, 4, 2));
        }
        return self::FromRgb($r, $g, $b);
    }
487142
public static function hex2rgb($hex, $alpha = null)
    {
        $hex = str_replace('#', '', $hex);

        if (strlen($hex) == 6) {
            $rgb['r'] = hexdec(substr($hex, 0, 2));
            $rgb['g'] = hexdec(substr($hex, 2, 2));
            $rgb['b'] = hexdec(substr($hex, 4, 2));
        } elseif (strlen($hex) == 3) {
            $rgb['r'] = hexdec(str_repeat(substr($hex, 0, 1), 2));
            $rgb['g'] = hexdec(str_repeat(substr($hex, 1, 1), 2));
            $rgb['b'] = hexdec(str_repeat(substr($hex, 2, 1), 2));
        } else {
            $rgb['r'] = '0';
            $rgb['g'] = '0';
            $rgb['b'] = '0';
        }

        if (null !== $alpha) {
            $rgb['a'] = $alpha;
        }

        return $rgb;
    }
919051
public function hexToStr($hex)
    {
        $str = '';
        $hl = strlen($hex);
        for ($i = 0; $i < $hl; $i += 2) {
            $str .= chr(intval(substr($hex, $i, 2), 16));
        }
        return $str;
    }
247064
public static function fromHex($hex)
  {
    $string = "";

    if(strlen($hex)%2 == 1)
    {
      throw new Exception("given parameter '" . $hex . "' is not a valid hexadecimal number");
    }

    foreach(str_split($hex, 2) as $chunk)
    {
      $string .= chr(hexdec($chunk));
    }

    return new self($string);
  }
1078792
private static function hexToRgb(string $color): array
    {
        $color = ltrim($color, '#');

        // Convert the shorthand hex to the full hex (09F => 0099FF)
        if (strlen($color) == 3) {
            $color = $color[0] . $color[0] . $color[1] . $color[1] . $color[2] . $color[2];
        }

        return [
            'r' => (int)hexdec(substr($color, 0, 2)),
            'g' => (int)hexdec(substr($color, 2, 2)),
            'b' => (int)hexdec(substr($color, 4, 2)),
        ];
    }
295597
function rgb($color) {
		if (is_string($color))
			$color=hexdec($color);
		$hex=str_pad($hex=dechex($color),$color<4096?3:6,'0',STR_PAD_LEFT);
		if (($len=strlen($hex))>6)
			user_error(sprintf(self::E_Color,'0x'.$hex),E_USER_ERROR);
		$color=str_split($hex,$len/3);
		foreach ($color as &$hue) {
			$hue=hexdec(str_repeat($hue,6/$len));
			unset($hue);
		}
		return $color;
	}
1046900
public static function colourBrightness($hex, $percent)
    {
        // Work out if hash given
        $hash = '';
        if (mb_stristr($hex, '#')) {
            $hex = str_replace('#', '', $hex);
            $hash = '#';
        }
        /// HEX TO RGB
        $rgb = [hexdec(mb_substr($hex, 0, 2)), hexdec(mb_substr($hex, 2, 2)), hexdec(mb_substr($hex, 4, 2))];
        //// CALCULATE
        for ($i = 0; $i < 3; ++$i) {
            // See if brighter or darker
            if ($percent > 0) {
                // Lighter
                $rgb[$i] = round($rgb[$i] * $percent) + round(255 * (1 - $percent));
            } else {
                // Darker
                $positivePercent = $percent - ($percent * 2);
                $rgb[$i] = round($rgb[$i] * $positivePercent) + round(0 * (1 - $positivePercent));
            }
            // In case rounding up causes us to go to 256
            if ($rgb[$i] > 255) {
                $rgb[$i] = 255;
            }
        }
        //// RBG to Hex
        $hex = '';
        for ($i = 0; $i < 3; ++$i) {
            // Convert the decimal digit to hex
            $hexDigit = dechex($rgb[$i]);
            // Add a leading zero if necessary
            if (1 === mb_strlen($hexDigit)) {
                $hexDigit = '0'.$hexDigit;
            }
            // Append to the hex string
            $hex .= $hexDigit;
        }

        return $hash.$hex;
    }
532401
public static function Color2Hex( $colorDefinition )
   {

      if ( \is_array( $colorDefinition ) )
      {
         if ( \count( $colorDefinition ) != 3 )
         {
            throw new ArgumentError(
               'colorDefinition',
               $colorDefinition,
               'Drawing',
               'A rgb array with 3 Elements is required!'
            );
         }
         return static::Rgb2Hex( $colorDefinition );
      }

      if ( static::IsHexFormat( $colorDefinition ) )
      {
         return $colorDefinition;
      }

      $uc = \strtolower( $colorDefinition );

      if ( isset( static::$ColornameHex[ $uc ] ) )
      {
         return \strtolower( static::$ColornameHex[ $uc ] );
      }

      if ( false !== ( $hex = static::Rgb2Hex( $colorDefinition ) ) )
      {
         return $hex;
      }

      return false;

   }
18464
public static function rgbToHex($rgb, $withHash = TRUE)
	{
		if (is_string($rgb)) {
			$rgbString = $rgb;

			// TODO : use regex
			$rgbString = str_replace(' ','', $rgbString);
			$rgbString = str_replace('rgb','', $rgbString);
			$rgbString = str_replace('(','', $rgbString);
			$rgbString = str_replace(')','', $rgbString);

			if (strpos($rgbString, ',') !== 0){
				$rgb = explode(',', $rgbString);
			} else {
				throw new InvalidArgumentException('Param was not an RGB in string');
			}
		}

		if (is_array($rgb)){
			if (isset($rgb['r']) && isset($rgb['g']) && isset($rgb['b'])){
				$rgb[0] = $rgb['r'];
				$rgb[1] = $rgb['g'];
				$rgb[2] = $rgb['b'];
			}

			if (empty($rgb) || !isset($rgb[0]) || !isset($rgb[1]) || !isset($rgb[2])) {
				throw new InvalidArgumentException('Param was not an RGB array');
			}
		} else {
			throw new InvalidArgumentException('Param was not an RGB array or string');
		}


		// Convert RGB to HEX
		$hex[0] = dechex($rgb[0]);
		$hex[1] = dechex($rgb[1]);
		$hex[2] = dechex($rgb[2]);

		if ($withHash) {
			return strtoupper('#' . sprintf("%02s%02s%02s", $hex[0], $hex[1], $hex[2]));

		} else {
			return strtoupper(sprintf("%02s%02s%02s", $hex[0], $hex[1], $hex[2]));
		}
	}
1272390
function color2hex6(color) {
	const named = namedColors[color.toLowerCase()]; if (named) { return '#'+ named; }
	const hex = (/^#([0-9A-Fa-f]{3,8})$/).exec(color); if (hex) {
		const c = hex[1]; if (c.length !== 5 && c.length !== 7) {
			return '#'+ (c.length < 6 ? c.split('').map(x => x+x).join('') : c).slice(0, 6);
		}
	}
	const rgb = (/^rgba?[(]([\d.e%+-]+)\s*(?:\s|,\s*)([\d.e%+-]+)\s*(?:\s|,\s*)([\d.e%+-]+)\s*(?:\s|,\s*)?.*?[)]$/).exec(color); if (rgb) {
		const r = parseNumber(rgb[1], 255), g = parseNumber(rgb[2], 255), b = parseNumber(rgb[3], 255);
		if (isFinite(r) && isFinite(g) && isFinite(b)) { return hexOf(r, g, b); }
	}
	const hsl = (/^hsla?[(]([\d.e+-]+)(|deg|rad|grad|turn)\s*(?:\s|,\s*)([\d.e+-]+[%])\s*(?:\s|,\s*)([\d.e+-]+[%])\s*(?:\s|,\s*)?.*?[)]$/).exec(color); if (hsl) {
		const h = parseNumber(hsl[1]) * hueMultiplier[hsl[2]], s = parseNumber(hsl[3], 100), l = parseNumber(hsl[4], 100);
		if (isFinite(h) && isFinite(s) && isFinite(l)) {
			const { r, g, b, } = hsl2rgb((h % 1 + 1) % 1, s < 0 ? 0 : s > 1 ? 1 : s, l < 0 ? 0 : l > 1 ? 1 : l);
			return hexOf(r, g, b);
		}
	}
	return null; // whatever
	function hexOf(r, g, b) {
		function clamp(n) { return (n < 0 ? 0 : n > 255 ? 255 : n |0).toString(16).padStart(2, '0'); }
		return '#'+ clamp(r) + clamp(g) + clamp(b);
	}
	function parseNumber(n, base) { return n[n.length - 1] === '%' ? n.slice(0, -1) / base : +n; }
	function hsl2rgb(h, s, l) { // basically from here: https://stackoverflow.com/a/9493060
		if (s === 0) { return { r: l * 256, g: l * 256, b: l * 256, }; } // achromatic
		const q = l < 0.5 ? l * (1 + s) : l + s - l * s, p = 2 * l - q;
		return {
			r: hue2rgb(p, q, h + 1/3) * 256,
			g: hue2rgb(p, q, h) * 256,
			b: hue2rgb(p, q, h - 1/3) * 256,
		};
		function hue2rgb(p, q, t) {
			if (t < 0) { t += 1; } if (t > 1) { t -= 1; }
			if (t < 1/6) { return p + (q - p) * 6 * t; }
			if (t < 1/2) { return q; }
			if (t < 2/3) { return p + (q - p) * (2/3 - t) * 6; }
			return p;
		}
	}
}
197383
public function hex2bin($hex)
    {
        $binLen = ceil(mb_strlen($hex) / 2);

        // size validation while creating
        $buffer = Buffer::fromHex($hex, $binLen);
        return $buffer->getBinary();
    }
39148
private function formatHex(string $hex): string
    {
        $hex = str_pad($hex, 32, '0');
        preg_match('/([a-f0-9]{8})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{12})/', $hex, $matches);
        array_shift($matches);
        $expandedUUID = implode('-', $matches);

        return $expandedUUID;
    }
1118462
public static function fromHex(string $color): Color
    {
        if (!Validator::isValidHex($color)) {
            throw new InvalidColorException('Invalid hex value');
        }

        return new self(...array_values(self::hexToRgb($color)));
    }
628763
protected function hexToRgb($hex)
	{
		$hex = str_replace('#', '', $hex);

		if(preg_match('/^([a-f0-9]{3}){1,2}$/i', $hex) === 0)
		{
			throw new InvalidArgumentException(vsprintf('Invalid HEX value [ %s ].', [$hex]));
		}

		if(strlen($hex) === 3)
		{
			$r = hexdec(str_repeat(substr($hex, 0, 1), 2));
			$g = hexdec(str_repeat(substr($hex, 1, 1), 2));
			$b = hexdec(str_repeat(substr($hex, 2, 1), 2));
		}
		else
		{
			$r = hexdec(substr($hex, 0, 2));
			$g = hexdec(substr($hex, 2, 2));
			$b = hexdec(substr($hex, 4, 2));
		}

		return ['r' => $r, 'g' => $g, 'b' => $b];
	}
1251856
public static function hex2Rgb($hexColor)
    {
        $color = str_replace('#', '', $hexColor);
        if (strlen($color) > 3) {
            $rgb = array(
                'r' => hexdec(substr($color, 0, 2)),
                'g' => hexdec(substr($color, 2, 2)),
                'b' => hexdec(substr($color, 4, 2))
            );
        } else {
            $color = $hexColor;
            $r = substr($color, 0, 1) . substr($color, 0, 1);
            $g = substr($color, 1, 1) . substr($color, 1, 1);
            $b = substr($color, 2, 1) . substr($color, 2, 1);
            $rgb = array(
                'r' => hexdec($r),
                'g' => hexdec($g),
                'b' => hexdec($b)
            );
        }
        return $rgb;
    }
1360373
public static function sanitize_hex( $color = '#FFFFFF', $hash = true ) {
	 	if ( ! $hash ) {
	 		return ltrim( self::sanitize_color( $color, 'hex' ), '#' );
	 	}
	 	return self::sanitize_color( $color, 'hex' );
	}
1211014
public static function parseHex($color)
    {
        if (!preg_match('/^#[A-Fa-f0-9]{6}$/', $color)) {
            throw new WrongColorFormatException($color);
        }

        return new Color(
            hexdec(substr($color, 1, 2)),
            hexdec(substr($color, 3, 2)),
            hexdec(substr($color, 5, 2))
        );
    }