Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"00" becomes "0" in PHP function, but it must be "00" for RGB to work. How?

Tags:

php

colors

rgb

zero

this PHP RGB brightness altering function works partially:

enter image description here

It misses one zero "0" at the end: so it should be "00" How to solve this?

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

How to fix this? Much appreciated!

The function brightness();

### 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);
}
like image 478
Sam Avatar asked Jan 21 '23 07:01

Sam


2 Answers

return sprintf("#%02x%02x%02x", $r, $g, $b);
like image 109
EboMike Avatar answered Jan 26 '23 01:01

EboMike


This has been discussed here in the comments:

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

wrap each of r,g,b in the zfill/zeropad function.

like image 33
sleeplessnerd Avatar answered Jan 26 '23 00:01

sleeplessnerd