Image
PHP Code Examples
[Download]
<?php
// Generates a JPG image of a clock showing the current time.

// Clock parameters.
define('OX', 150); define('OY', 150);  // Origin
define('RAD', 150); // Face radius.

// Convert a point in clock units to rectangular.  The clock units are 
// minutes clockwise from noon, and the distance from the center of the
// clock face.
function rect($mins, $dist)
{
	// Get the angle.
	$mins = 15 - $mins;
	if($mins < 0) $mins += 60;
	$ang = deg2rad(6*$mins);

	$x = OX + round($dist*cos($ang));
	$y = OY - round($dist*sin($ang));

	return array($x, $y);
}

// Draw a hand.  The length is a fraction of RAD, 
function hand($im, $length, $mins, $line_color, $thick = FALSE)
{
	$sep = round(0.02*RAD);

	list($sx, $sy) = rect($mins, $sep);
	list($ex, $ey) = rect($mins, $sep + round($length*RAD));

	if($thick) {
		// This computes one of 8 portions of the clock face, 
		// essentially the eight compass points, north numbered
		// zero, and increasing clockwise.
		if($mins > 60-3.75) $mins = 60 - $mins;
		else $mins += 3.75;
		$portion = round($mins / 7.5);

		// This assigns adjustments of the endpoint coordinates
		// based on the portion.  This allows a thicker line with
		// some attempt to angle the flat sides appropriately.
		$ta = array(-1, -1, 0, 1, 1, 1, 0, -1, -1);
		$dx = $ta[$portion];
		$ta = array(0, -1, -1, -1, 0, 1, 1, 1, 0);
		$dy = $ta[$portion];

		// Draw the fat line, which is now actually a rectangle.
		imagefilledpolygon($im, 
				   array($sx + $dx, $sy + $dy,
					 $sx - $dx, $sy - $dy,
					 $ex - $dx, $ey - $dy,
					 $ex + $dx, $ey + $dy),
				   4, $line_color);
	} else
		imageline($im, $sx, $sy, $ex, $ey, $line_color);	
}

// Set up for images.
header ("Content-type: image/jpeg");
$im = @ImageCreate (2*RAD + 5, 2*RAD + 5)
    or die ("Cannot Initialize new GD image stream");
ImageColorAllocate ($im, 175, 240, 230);

//Draw the numbers.
$num_color = ImageColorAllocate ($im, 0,0,255);
for($i = 1; $i <= 12; ++$i) {
	list($x, $y) = rect(5*$i, round(0.9*RAD));
	ImageString($im, 5, $x, $y, "$i", $num_color);
}

// Draw the hands.
$ms_color = ImageColorAllocate ($im, 5, 200, 5);
$sec_color = ImageColorAllocate ($im, 200, 5, 5);
$now = getdate();
$hours = $now['hours'];
if($hours >= 12) $hours -= 12;
hand($im, 0.4, 5*$hours, $ms_color, TRUE);
hand($im, 0.7, $now['minutes'], $ms_color, TRUE);
hand($im, 0.8, $now['seconds'], $sec_color);

ImageJPEG ($im);
?>