In questo articolo vorrei presentare due semplici funzioni di utility per la conversione dei colori dal formato esadecimale in RGB e viceversa. Le possibili applicazioni sono molteplici, per esempio in un tema di WordPress munito di un color picker. Vediamole insieme.
La prima funzione estrae i sei valori che compongono una stringa esadecimale a due a due e restituisce un array associativo con i valori corrispondenti di rosso, verde e blu ottenuti usando la funzione hexdec()
:
function hexToRGB ($hexcode)
{
$redhex = substr( $hexcode, 0, 2 );
$greenhex = substr( $hexcode, 2, 2 );
$bluehex = substr( $hexcode, 4, 2 );
$r = hexdec($redhex);
$g = hexdec($greenhex);
$b = hexdec($bluehex);
return array( 'red' => $r, 'green' => $g, 'blue' => $b );
}
La seconda funzione parte da un array associativo RGB e restituisce una stringa esadecimale ottenuta utilizzando le funzioni sprintf()
e round()
:
function rgbToHex ($rgb)
{
$r = $rgb['red'];
$g = $rgb['green'];
$b = $rgb['blue'];
$rhex = sprintf( "%02X", round($r) );
$ghex = sprintf( "%02X", round($g) );
$bhex = sprintf( "%02X", round($b) );
$hex = $rhex.$ghex.$bhex;
return $hex;
}