<?php
    // Taken from the book 'CGI programming' by Shishir Gundavaram
    // and 'translated' from Perl to PHP by G. Knauf.
    // Print out time as analog clock png picture. 
    // to view source call with: gd_clock.php?viewsource=1
    // call f.e. with: gd_clock.php?trans=1
    // v0.11 20-Sep-2004, by G. Knauf <efash@gmx.net>
    if ($_GET['viewsource']) {
        echo highlight_string(file_get_contents($_SERVER['SCRIPT_FILENAME']));
        die;
    }
    extension_loaded('gd') or die ("Error: GD extension not loaded!"); 
    $max_length = 150;
    $marker = 5;
    $origin_x = $origin_y = $max_length / 2;
    $radius = $max_length / 2 - 2;
    $hour_segment = $radius * 0.50;
    $minute_segment = $radius * 0.80;
    $deg_to_rad = (atan2 (1, 1) * 4) / 180;

    $im = @ImageCreate ($max_length, $max_length);
    $black = ImageColorAllocate ($im, 0, 0, 0);
    $red = ImageColorAllocate ($im, 255, 0, 0);
    $green = ImageColorAllocate ($im, 0, 255, 0);
    $blue = ImageColorAllocate ($im, 0, 0, 255);
    if ($_GET['trans'])
        ImageColorTransparent($im, $black);

    $lt = localtime ();
    $hour_angle = ($lt[2] + ($lt[1] / 60) - 3) * 30 * $deg_to_rad;
    $minute_angle = ($lt[1] + ($lt[0] / 60) - 15) * 6 * $deg_to_rad;

    ImageArc ($im, $origin_x, $origin_y, $max_length - 2, $max_length - 2, 0, 360, $blue);
    for ($loop=0; $loop < 360; $loop = $loop + 30) {
        $degrees = $loop * $deg_to_rad;
        ImageLine ($im,  $origin_x + (($radius - $marker) * cos ($degrees)),
                $origin_y + (($radius - $marker) * sin ($degrees)),
                $origin_x + ($radius * cos ($degrees)),
                $origin_y + ($radius * sin ($degrees)),
                $red  );
    }
    ImageLine ($im, $origin_x, $origin_y, 
            $origin_x + ($hour_segment * cos ($hour_angle)),
            $origin_y + ($hour_segment * sin ($hour_angle)),
            $green  );
    ImageLine ($im, $origin_x, $origin_y,
            $origin_x + ($minute_segment * cos ($minute_angle)),
            $origin_y + ($minute_segment * sin ($minute_angle)),
            $green  );
    ImageArc ($im, $origin_x, $origin_y, 6, 6, 0, 360, $red);
    ImageFill ($im, $origin_x + 1, $origin_y + 1, $red);

    Header("Content-type: image/png");
    ImagePng($im);
    ImageDestroy($im);
?>
Published in: PHP
Download

Related snippets