conversion couleurs

Convertir une couleur HTML en composantes RGB

Comment transformer une couleur en notation HTML vers du RGB

rgb html, html rgb, couleur html, notation html couleur, conversion couleur html, php html to rgb, conversion html rgb, fonction rgb php, php to rgb, conversion code html en rgb php, php fonction rgb, not provided, couleur en int

La fonction html2rgb suivante permet de transformer une couleur en notation html vers un tableau contenant les composantes RGB de la couleur.

Cette fonction supporte la notation html à 3 et 6 caractères et fonctionne avec ou sans le # initial de la couleur html.

La fonction retourne false si jamais la chaine de caractère fait plus de 6 caractères (sans compter l'éventuel #).

Fonction html2rgb


<?php
/**
* Retourne les composantes RGB d'une couleur html
*
* @param string $color
* @return mixed array
*/
function html2rgb ($color)
{
/*On supprime le # eventuel de la couleur html*/
if ($color[0] == '#')
{
$color = substr($color, 1);
}
$strlen = strlen($color);
/*Si on utilise la notation de 6 caractères*/
if ($strlen === 6)
{
$color = array(
$color[0].$color[1],
$color[2].$color[3],
$color[4].$color[5]
);
}
/*Si on utilise la notation html à 3 caractères*/
elseif ($strlen === 3)
{
$color = array(
$color[0].$color[0],
$color[1].$color[1],
$color[2].$color[2]
);
}
else
{
return false;
}
foreach ($color as &$c)
{
$c = hexdec($c);
}
return $color;
}
?>

Exemple de conversion avec html2rgb

Voici quelques exemples de conversion de couleur html en code valeurs RGB :


<?php
var_dump(html2rgb ('28000a'));
/**
* array
* 0 => int 40
* 1 => int 0
* 2 => int 10
*/
var_dump(html2rgb ('#28000a'));
/**
* array
* 0 => int 40
* 1 => int 0
* 2 => int 10
*/
var_dump(html2rgb ('#280'));
/**
* array
* 0 => int 34
* 1 => int 136
* 2 => int 0
*/
var_dump(html2rgb ('280'));
/**
* array
* 0 => int 34
* 1 => int 136
* 2 => int 0
*/
var_dump(html2rgb ('#28032435465'));
/**
* false
*/
?>

Image : Marco Braun

 
 

b1n@sp1n