Core PHP

Drawing a Fractal with GD

The GD library allows programmers to draw simple geometric primitives.

DrawFractal.php

<?php
// Calculate the image size for a given width with 10 pixels of padding
$iImageWidth = 800;
$iFractalWidth = $iImageWidth - 20;
$iFractalHeight = Round(($iFractalWidth/2)*Sqrt(3));
$iImageHeight = $iFractalHeight + 20;

$qaVertices = [
  array('x' => $iImageWidth/2, 'y' =>  10),
  array('x' =>   10, 'y' => $iImageHeight - 10),
  array('x' => $iImageWidth - 10, 'y' => $iImageHeight - 10)];

$qImage = ImageCreateTrueColor($iImageWidth, $iImageHeight);
$qWhite = ImageColorExactAlpha($qImage, 255, 255, 255, 0);
ImageFill($qImage, 0, 0, $qWhite);

$x = $qaVertices[0]['x'];
$y = $qaVertices[0]['y'];

for ($i = 0; $i < 400000; $i++) {
  $iColorIndex = ImageColorAt($qImage, Round($x), Round($y));
  $iaColor = ImageColorsForIndex($qImage, $iColorIndex);
  $iaColor["red"] = (7*$iaColor["red"])/8;
  $iaColor["green"] = (7*$iaColor["green"])/8;
  $iaColor["blue"] = (7*$iaColor["blue"])/8;
  $qOverColor = ImageColorExactAlpha($qImage,$iaColor["red"],$iaColor["green"],$iaColor["blue"],0);

  ImageSetPixel($qImage, round($x), round($y), $qOverColor);
  $iVertex = Rand(0, 2);
  $x = ($x + $qaVertices[$iVertex]['x']) / 2;
  $y = ($y + $qaVertices[$iVertex]['y']) / 2;
}

Header('Content-Type: image/png');
ImagePng($qImage);
ImageDestroy($qImage);
?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.