Following Color class will allow you to convert colors from RGB to hex and back
 1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 class  Color 
{ 
  /** int $red */ 
   public  $red ; 
 
   /** int $green */ 
   public  $green ; 
 
   /** int $blue */ 
   public  $blue ; 
 
   /**
     * Color constructor.
    * @param $red
    * @param $green
    * @param $blue
    */ 
  public  function  __construct ( $red ,  $green ,  $blue ) 
   { 
       $this -> red  =  $red ; 
       $this -> green  =  $green ; 
       $this -> blue  =  $blue ; 
   } 
 
   // ...
  } 
Copy Convert from HEX string to RGB add this function to our class
 1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 public  static  function  convertToRGB ( $hex ) 
{ 
    $hex  =  ltrim ( $hex ,  "#" ); 
 
     if  ( ! ctype_xdigit ( $hex )) 
         throw  new  NotHexException (); 
 
     $red  =  hexdec ( substr ( $hex ,  0 ,  2 )); 
     $green  =  hexdec ( substr ( $hex ,  2 ,  2 )); 
     $blue  =  hexdec ( substr ( $hex ,  4 ,  2 )); 
 
     return  new  Color ( $red ,  $green ,  $blue ); 
 } 
Copy This is how you can convert from rgb back to HEX string.
 1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 public  static  function  convertToHex ( Color  $color ) 
{ 
    $red  =  dechex ( $color -> red ); 
     if  ( strlen ( $red )  <  2 )  $red  =  '0'  .  $red ; 
 
     $green  =  dechex ( $color -> green ); 
     if  ( strlen ( $green )  <  2 )  $green  =  '0'  .  $green ; 
 
     $blue  =  dechex ( $color -> blue ); 
     if  ( strlen ( $blue )  <  2 )  $blue  =  '0'  .  $blue ; 
 
     return  '#'  .  $red  .  $green  .  $blue ; 
 } 
Copy One thing is missing and itβs exception which is used in convertToRGB function:
1
 2
 3
 4
 5
 6
 7
 class  NotHexException  extends  \Exception 
{ 
  public  function  __construct ( $message  =  "String you have provided is not HEX" ,  $code  =  0 ,  Throwable  $previous  =  null ) 
   { 
       parent :: __construct ( $message ,  $code ,  $previous ); 
   } 
 } 
Copy To use it
1
 2
 3
 4
 use  MayMeow\PHPColor\Color ; 
// ...
 $color  =  new  Color ( 198 ,  255 ,  32 ); 
$hex  =  Color :: convertToHex ( $color );  //#c6ff20
 
Copy and back to RGB
1
 2
 3
 4
 5
 6
 7
 8
 use  MayMeow\PHPColor\Color ; 
// ...
 try  { 
    $rgb  =  Color :: convertToRGB ( $hex );  // color object: Color(198, 255, 32)
  }  catch  ( \MayMeow\PHPColor\Exceptions\NotHexException  $exception ) 
{ 
    // do something, echo message or log ...
  } 
Copy Photo by Sharon McCutcheon  on Unsplash