Home > PHP

RGBの値を16進数に変換

 かつてのPhotoshopにはRGBとCMYKの値を設定して色を作り出していたのですが、最近では16進数を使って色を作ることが多いです。というのもWebページの中では16進数の方が使いやすい構造になっているからです。
 そんなわけでRGBの0から255までの値をWebに特化した16進数になるようにするプログラムです。
<?php
//  RGBを16進数に変換
$red = rand(0,255);
$green = rand(0,255);
$blue = rand(0,255);

$color16 = change16_color($red, $green, $blue);
print "<div style='background-color:".$color16."'>これだ!</div>";

function change16_color ($red,$green,$blue) {

    #  16進数にそれぞれ変換
    $red = dechex($red);
    $green = dechex($green);
    $blue = dechex($blue);
    
    if (strlen($red) == 1) { $red = $red.$red; }
    if (strlen($green) == 1) { $green = $green.$green; }
    if (strlen($blue) == 1) { $blue = $blue.$blue; }
    
    $color16 = '#'."$red$green$blue";
    return $color16;
    
}

?>

  こんな感じです。dechexという便利な関数がPHPにはありました。