PHP rgb2hex

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP rgb2hex相关的知识,希望对你有一定的参考价值。

function rgb2hex($r, $g, $b, $uppercase=false, $shorten=false)
{
  // The output
  $out = "";
  
  // If shorten should be attempted, determine if it is even possible
  if ($shorten && ($r + $g + $b) % 17 !== 0) $shorten = false;
  
  // Red, green and blue as color
  foreach (array($r, $g, $b) as $c)
  {
    // The HEX equivalent
    $hex = base_convert($c, 10, 16);
    
    // If it should be shortened, and if it is possible, then
    // only grab the first HEX character
    if ($shorten) $out .= $hex[0];
    
    // Otherwise add the full HEX value (if the decimal color
    // is below 16 then we have to prepend a 0 to it)
    else $out .= ($c < 16) ? ("0".$hex) : $hex;
  }
  // Package and away we go!
  return $uppercase ? strtoupper($out) : $out;
}

echo "#", rgb2hex(250, 123, 0, true), // Gives: #FA7B00
 "<br>#", rgb2hex(170, 0, 255), // Gives: #aa00ff
 "<br>#", rgb2hex(170, 0, 255, false, true); // Gives: #a0f

以上是关于PHP rgb2hex的主要内容,如果未能解决你的问题,请参考以下文章