<?php

//All portions of this file (c) Andrew Bell 2007 unless indicated otherwise

$x 600//dimensions of our picture
$y 300;

$max_iter 100;
$max_rad 2//max value before we determine that the point has escaped

$gd imagecreatetruecolor($x$y);

//so now we traverse each pixel in our picture
for ($i 0$i $y$i++) //outer loop: up to down
{
  for (
$j 0$j $x$j++) //inner loop: left to right
  
{
    
$iter 0;
    
$a0 = (4/$x) * $j 3;        //set a nice zoom and center for our fractal and convert
    
$b0 = ((2/$y) * $i 1) * -1//from pixel position to actual value on the complex plane
   
    
$a 0//the complex number c is split into its real and imaginary parts
    
$b 0//$a is the real part, $b is the imaginary part

    
while(($iter $max_iter) && (($a $a $b $b) < $max_rad $max_rad)) //iterate until our point escapes
    
{                                                                         //or we run out of iterations
      
$a_new $a $a $b $b $a0//here's the guts of the thing: z_n+1(c) = z_n ^2 + c
      
$b_new $a $b $b0;       //if this diverges, the point is not in the Mandelbrot set

      
$a $a_new//the reason for these _new vars is in case we still need the originals
      
$b $b_new//after we've calculad the new values, eg. to calculate $b

      
$iter++;
    }
    
    if(
$iter != $max_iter//colour me in if i escaped :)
    
{
      
//$col_frac = floor(255*($max_iter/$iter));                              //here's my original simple
      //$pixel_col = imagecolorallocate($gd, $col_frac, $col_frac, $col_frac); //greyscalecolouring method

      
$rgb HSV_TO_RGB($iter/$max_iter11);                              //quick and dirty way of colouring: hue
      
$pixel_col imagecolorallocate($gd$rgb['R'], $rgb['G'], $rgb['B']); //is a linear function of escape iteration

      
imagesetpixel($gd$j$i$pixel_col);
    }
  }
}  
 
//I did not write the following function. It is from:
// http://www.actionscript.org/forums/archive/index.php3/t-50746.html
function HSV_TO_RGB ($H$S$V// HSV Values:Number 0-1
// RGB Results:Number 0-255
  
$RGB = array();

  if(
$S == 0)
  {
    
$R $G $B $V 255;
  }
  else
  {
    
$var_H $H 6;
    
$var_i floor$var_H );
    
$var_1 $V * ( $S );
    
$var_2 $V * ( $S * ( $var_H $var_i ) );
    
$var_3 $V * ( $S * (- ( $var_H $var_i ) ) );

    if (
$var_i == 0) { $var_R $V $var_G $var_3 $var_B $var_1 ; }
    else if (
$var_i == 1) { $var_R $var_2 $var_G $V $var_B $var_1 ; }
    else if (
$var_i == 2) { $var_R $var_1 $var_G $V $var_B $var_3 ; }
    else if (
$var_i == 3) { $var_R $var_1 $var_G $var_2 $var_B $V ; }
    else if (
$var_i == 4) { $var_R $var_3 $var_G $var_1 $var_B $V ; }
    else { 
$var_R $V $var_G $var_1 $var_B $var_2 ; }

    
$R $var_R 255;
    
$G $var_G 255;
    
$B $var_B 255;
  }

  
$RGB['R'] = $R;
  
$RGB['G'] = $G;
  
$RGB['B'] = $B;

  return 
$RGB;
}

header('Content-Type: image/png'); //set headers and output our lovely fractal!
imagepng($gd);

?>