正 文

使用PHP 5.0创建图形的巧妙方法


www.7dspace.com  更新日期:2006-1-13 1:25:50  七度空间


  这个库的代码如清单 1 所示。

  清单 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 ) );
  }
}
?>

  测试代码如清单 2 所示:

  清单 2. 基本图形库的测试代码

<?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" );
?>

  这个测试程序创建了一个图形环境。然后创建几条线,它们指向不同的方向,具有不同的颜色。然后,render 方法可以将它们画到图形平面上。最后,这段代码将这个图像保存为 test.png。

  在本文中,都是使用下面的命令行解释程序来运行这段代码,如下所示:

% php test.php
%

  图 2 显示了所生成的 test.png 文件在 Firefox 中的样子。

  图2. 简单的图形对象测试

简单的图形对象测试

  这当然不如蒙娜丽莎漂亮,但是可以满足目前的工作需要。

8页,页码:[1] [2] [3] [4] [5] [6] [7] [8] 

上一篇:把你的摄像头架到网上去
下一篇:照片处理:钻戒金属质感完美修复
标题:使用PHP 5.0创建图形的巧妙方法 作者:Jack Herrington 来源:ibm ( 责任编辑:7dspace )
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐