<?php

// Width of the output image
define('WIDTH',  250);

// Height of the output image
define('HEIGHT'250);

// The number of colors to generate
define('COLORS'50);

// Output filename
define('OUTPUT''voronoi.png');

// ------------------------------------

// Choose a list of random points with random colors
$rand_points = array();
for (
$i 0$i COLORS$i++) {
    
$rand_points[] = array('x' => mt_rand(0WIDTH 1),
                           
'y' => mt_rand(0HEIGHT 1),
                           
'c' => mt_rand(00xffffff));
}

/*
 * Not the most efficient algorithm, but it's easy to understand and it works.
 * Loop through all pixels of the image, find the closest random point, then
 * set the color of the pixel to the color of that point.
 *
 * Requires WIDTH * HEIGHT * COLORS iterations on average, which does get ugly.
 */

$im imageCreateTrueColor(WIDTHHEIGHT);
for (
$y 0$y HEIGHT$y++) {
    for (
$x 0$x WIDTH$x++) {
        
imageSetPixel($im$x$yshortest_distance($x$y$rand_points));
    }
}

imagePNG($imOUTPUT);
imageDestroy($im);

function 
shortest_distance($x$y, array $pts)
{
    
$shortest WIDTH HEIGHT;
    
$return   '';
    for (
$i 0$i COLORS$i++) {
        
$dist sqrt(pow($pts[$i]['x'] - $x2) + pow($pts[$i]['y'] - $y2));
        if (
$dist $shortest) {
            
$shortest $dist;
            
$return $pts[$i]['c'];
            if (
$dist === 0) {
                break;
            }
        }
    }
    return 
$return;
}