【问题标题】:"00" becomes "0" in PHP function, but it must be "00" for RGB to work. How?“00”在 PHP 函数中变为“0”,但 RGB 必须为“00”才能工作。如何?
【发布时间】:2011-07-09 05:09:47
【问题描述】:

这个 PHP RGB 亮度改变功能部分起作用:

最后少了一个零“0”:所以应该是“00”怎么解决?

$color = "#a7a709";  // constant 
$color1 = brightness($color,+25); // brighter, echoes #c0c022, correct RGB value
$color2 = brightness($color,-25); // darker echoes #8e8e0, incorrect RGB value!!

如何解决这个问题? 非常感谢!

函数亮度();

### CREDITS go to Cusimar9 who wrote this
function brightness($colourstr, $steps) {
  $colourstr = str_replace('#','',$colourstr);
  $rhex = substr($colourstr,0,2);
  $ghex = substr($colourstr,2,2);
  $bhex = substr($colourstr,4,2);

  $r = hexdec($rhex);
  $g = hexdec($ghex);
  $b = hexdec($bhex);

  $r = max(0,min(255,$r + $steps));
  $g = max(0,min(255,$g + $steps));  
  $b = max(0,min(255,$b + $steps));

  return '#'.dechex($r).dechex($g).dechex($b);
}

【问题讨论】:

    标签: php colors rgb zero


    【解决方案1】:
    return sprintf("#%02x%02x%02x", $r, $g, $b);
    

    【讨论】:

    • 我在想if(strlen($r) == 1) $r = '0'.$r; 将它们带回字符串,并在指定的情况下添加字母,我现在有点好奇.. sprintf 是否使用太多开销或者哪个更有效?
    • ... 或 if ($r) < 10... 但恕我直言,这两个似乎都不那么优雅。
    • 好吧,sprintf 是一个本地函数,它只需要分配一个结果字符串。我认为它更有效。
    • @Sam:您只需将 return 声明替换为我发布的声明即可。
    • 把退货换成他放在那里的东西。
    【解决方案2】:

    这已在 cmets 中讨论过:

    http://php.net/manual/en/function.dechex.php

    将每个 r,g,b 包装在 zfill/zeropad 函数中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      • 2012-06-23
      相关资源
      最近更新 更多