Adding Colour To A Mandelbrot Set

I was looking for a way to introduce some colour into my example Drawing A Mandelbrot Set With Zend PDF.

The method I settled upon was to use HSV – Hue, Saturation, Value.

I’m not an expert on colour theory, so I may not be the best person to describe how it works. The best way I can though, is to describe it as a cylinder, round the circumference is the hue, the radius is the saturation, and the height is the value. For a detailed definition, read the Wikipedia entry on HSL and HSV.

I can pick a hue and value, then just vary the saturation to give a nice graduated colour version of the earlier grayscale example.

Blue Mandelbrot

Alternatively I can pick a value and saturation, and vary the hue to give a vivid rainbow style fractal.

Vivid Mandelbrot

To achieve the first, we replace the code in the loop that prepared the grayscale colours, and instead generate our $colours array with the following…

list($red, $green, $blue) = hsvToRgb(0.5, $grayLevel, 1);
$colours[$i] = new Zend_Pdf_Color_Rgb($red, $green, $blue);

Firstly we get the values for $red, $green and $blue for a hue of 0.5 (blue), our varying $graylevel between 0 and 1, and a $value of 1 for the most vivid colours. After this we create a Zend_Pdf_Color and store it in the $colours array to use later.

To achieve the latter we just change how we call the hsvToRgb function.

list($red, $green, $blue) = hsvToRgb($grayLevel, 1, 1);
$colours[$i] = new Zend_Pdf_Color_Rgb($red, $green, $blue);

Now, you may have noticed that there isn’t a function called hsvToRgb available to PHP. Just drop in the following code.

function hsvToRgb ($hue, $saturation, $value)
{
  $rgb = array($value, $value, $value);
  if ($saturation != 0) {
    $varH = $hue * 6;
    $varI = floor($varH);
    $var1 = $value * ( 1 - $saturation );
    $var2 = $value * ( 1 - $saturation * ( $varH - $varI ) );
    $var3 = $value * ( 1 - $saturation * (1 - ( $varH - $varI ) ) );
    if ($varI == 0) {
      $rgb = array($value, $var3, $var1);
    } else if ($varI == 1) {
      $rgb = array($var2, $value, $var1);
    } else if ($varI == 2) {
      $rgb = array($var1, $value, $var3);
    } else if ($varI == 3) {
      $rgb = array($var1, $var2, $value);
    } else if ($varI == 4) {
      $rgb = array($var3, $var1, $value);
    } else {
      $rgb = array($value, $var1, $var2);
    }
  }
  return $rgb;
}