网络编程 发布日期:2025/11/9 浏览次数:1

<?php
class GraphicsEnvironment
{
public $width;
public $height;
public $gdo;
public $colors = array();
public function __construct( $width, $height )
{
$this->width = $width;
$this->height = $height;
$this->gdo = imagecreatetruecolor( $width, $height );
$this->addColor( "white", 255, 255, 255 );
imagefilledrectangle( $this->gdo, 0, 0,
$width, $height,
$this->getColor( "white" ) );
}
public function width() { return $this->width; }
public function height() { return $this->height; }
public function addColor( $name, $r, $g, $b )
{
$this->colors[ $name ] = imagecolorallocate(
$this->gdo,
$r, $g, $b );
}
public function getGraphicObject()
{
return $this->gdo;
}
public function getColor( $name )
{
return $this->colors[ $name ];
}
public function saveAsPng( $filename )
{
imagepng( $this->gdo, $filename );
}
}
abstract class GraphicsObject
{
abstract public function render( $ge );
}
class Line extends GraphicsObject
{
private $color;
private $sx;
private $sy;
private $ex;
private $ey;
public function __construct( $color, $sx, $sy, $ex, $ey )
{
$this->color = $color;
$this->sx = $sx;
$this->sy = $sy;
$this->ex = $ex;
$this->ey = $ey;
}
public function render( $ge )
{
imageline( $ge->getGraphicObject(),
$this->sx, $this->sy,
$this->ex, $this->ey,
$ge->getColor( $this->color ) );
}
}
?>
<?php
require_once( "glib.php" );
$ge = new GraphicsEnvironment( 400, 400 );
$ge->addColor( "black", 0, 0, 0 );
$ge->addColor( "red", 255, 0, 0 );
$ge->addColor( "green", 0, 255, 0 );
$ge->addColor( "blue", 0, 0, 255 );
$gobjs = array();
$gobjs []= new Line( "black", 10, 5, 100, 200 );
$gobjs []= new Line( "blue", 200, 150, 390, 380 );
$gobjs []= new Line( "red", 60, 40, 10, 300 );
$gobjs []= new Line( "green", 5, 390, 390, 10 );
foreach( $gobjs as $gobj ) { $gobj->render( $ge ); }
$ge->saveAsPng( "test.png" );
?>
% php test.php %
图 2 显示了所生成的 test.png 文件在 Firefox 中的样子。
图2. 简单的图形对象测试
这当然不如蒙娜丽莎漂亮,但是可以满足目前的工作需要。