May's Blog

Following Color class will allow you to convert colors from RGB to hex and back

 1class Color
 2{
 3  /** int $red */
 4  public $red;
 5
 6  /** int $green */
 7  public $green;
 8
 9  /** int $blue */
10  public $blue;
11
12  /**
13   * Color constructor.
14   * @param $red
15   * @param $green
16   * @param $blue
17   */
18  public function __construct($red, $green, $blue)
19  {
20      $this->red = $red;
21      $this->green = $green;
22      $this->blue = $blue;
23  }
24
25  // ...
26}

Convert from HEX string to RGB add this function to our class

 1public static function convertToRGB($hex)
 2{
 3    $hex = ltrim($hex, "#");
 4
 5    if (!ctype_xdigit($hex))
 6        throw new NotHexException();
 7
 8    $red = hexdec(substr($hex, 0, 2));
 9    $green = hexdec(substr($hex, 2, 2));
10    $blue = hexdec(substr($hex, 4, 2));
11
12    return new Color($red, $green, $blue);
13}

This is how you can convert from rgb back to HEX string.

 1public static function convertToHex(Color $color)
 2{
 3    $red = dechex($color->red);
 4    if (strlen($red) < 2) $red = '0' . $red;
 5
 6    $green = dechex($color->green);
 7    if (strlen($green) < 2) $green = '0' . $green;
 8
 9    $blue = dechex($color->blue);
10    if (strlen($blue) < 2) $blue = '0' . $blue;
11
12    return '#' . $red . $green . $blue;
13}

One thing is missing and it’s exception which is used in convertToRGB function:

1class NotHexException extends \Exception
2{
3  public function __construct($message = "String you have provided is not HEX", $code = 0, Throwable $previous = null)
4  {
5      parent::__construct($message, $code, $previous);
6  }
7}

To use it

1use MayMeow\PHPColor\Color;
2// ...
3$color = new Color(198, 255, 32);
4$hex = Color::convertToHex($color); //#c6ff20

and back to RGB

1use MayMeow\PHPColor\Color;
2// ...
3try {
4    $rgb = Color::convertToRGB($hex); // color object: Color(198, 255, 32)
5} catch (\MayMeow\PHPColor\Exceptions\NotHexException $exception)
6{
7    // do something, echo message or log ...
8}

Photo by Sharon McCutcheon on Unsplash

#Colors #PHP #Daily #Rgb #Hex