eni
eni

Reputation: 695

Generate gradient color from PHP

I want to know how to build a function that give the code of an color and display a gradient of this color. For example:

function generate_color(int colorindex)
{  .......
   .......
   Generate 10  pale colors of this color.


}

Please help me

Upvotes: 3

Views: 6892

Answers (2)

Michael Robinson
Michael Robinson

Reputation: 29498

In the answer to this question lies your solution, only in Javascript...

Generate lighter/darker color in css using javascript

I'm not going to write it out, but a simple Google search for 'lighten hex colour php' yields:

function colourBrightness($hex, $percent) {
 // Work out if hash given
 $hash = '';
 if (stristr($hex,'#')) {
  $hex = str_replace('#','',$hex);
  $hash = '#';
 }
 /// HEX TO RGB
 $rgb = array(hexdec(substr($hex,0,2)), hexdec(substr($hex,2,2)), hexdec(substr($hex,4,2)));
 //// CALCULATE
 for ($i=0; $i<3; $i++) {
  // See if brighter or darker
  if ($percent > 0) {
   // Lighter
   $rgb[$i] = round($rgb[$i] * $percent) + round(255 * (1-$percent));
  } else {
   // Darker
   $positivePercent = $percent - ($percent*2);
   $rgb[$i] = round($rgb[$i] * $positivePercent) + round(0 * (1-$positivePercent));
  }
  // In case rounding up causes us to go to 256
  if ($rgb[$i] > 255) {
   $rgb[$i] = 255;
  }
 }
 //// RBG to Hex
 $hex = '';
 for($i=0; $i < 3; $i++) {
  // Convert the decimal digit to hex
  $hexDigit = dechex($rgb[$i]);
  // Add a leading zero if necessary
  if(strlen($hexDigit) == 1) {
  $hexDigit = "0" . $hexDigit;
  }
  // Append to the hex string
  $hex .= $hexDigit;
 }
 return $hash.$hex;
}

http://lab.pxwebdesign.com.au/?p=14

Your Google is just as good as mine!

Upvotes: 2

symcbean
symcbean

Reputation: 48357

The code Michael references is rather scary. But the solution is straightforward. It may be clearer if you consider simply a grey scale image:

 function create_pallette($start, $end, $entries=10)
 {
    $inc=($start - $end)/($entries-1);
    $out=array(0=>$start);
    for ($x=1; $x<$entries;$x++) {
      $out[$x]=$start+$inc * $x;
    }
    return $out;
 }

Only using a 3D vector (RGB) instead of a 1D vector.

C.

Upvotes: 5

Related Questions