Clever way to create graphics using PHP 5.0_PHP Tutorial
This article will show you how to build an object-oriented graphics layer using PHP. Using an object-oriented system can be used to build complex graphics much more easily than using the basic functionality provided in the standard PHP library.
I divide graphics editing programs into two categories: drawing programs, which draw an image pixel by pixel, and drawing programs, which provide a set of objects such as lines, ellipses, and Rectangles, you can use these objects to combine into a large image, such as a JPEG. Painting programs are great for pixel-level control. But for business graphics, a drawing program is a better way because most graphics are composed of rectangles, lines, and ellipses.
The basic drawing operations built into PHP are very similar to drawing programs. They are very powerful for drawing images; however, they are not suitable if you want your image to be a collection of objects. This article will show you how to build an object-oriented graphics library based on the PHP graphics library. You will use the object-oriented extensions provided in PHP V5.
With object-oriented graphics support, your graphics code is much easier to understand and maintain. You may also need to composite graphics into multiple types of media from a single graphics source: Flash movie, SVG, and so on.
Goal
Creating a graphical object library includes 3 main goals:
Switch from basic operations to objects
Rather than using imageline, imagefilledrectangle, and other graphics functions, this library should provide objects such as Line, Rectangle, and Oval that can be used to make images. It should also support the ability to build larger complex objects or group objects.
Can be sorted by z value
Drawing programs allow painters to move graphic objects up and down the surface of the drawing. This library is supposed to support placing an object in front of or behind another object: it uses a z-value that defines the height of the object from the drawing plane. Objects with larger z-values are drawn later and appear above those with smaller z-values.
Provide viewport conversion
Usually, the coordinate space of the data is different from the coordinate space of the image. The basic graphics operations in PHP operate on the coordinate plane of the image. The graphics library should support the viewport specification so that you can specify graphics in a coordinate system that is familiar to programmers and automatically scale to fit any image size.
Because there are so many features here, you'll write code step by step to show how the code adds functionality.
Basic knowledge
Let us first look at a graphics environment object and an interface called GraphicsObject, which is implemented using a Line class, and its function is to draw lines. UML is shown in Figure 1.
Figure 1. Graphical environment and graphical object interface
The GraphicsEnvironment class stores graphics objects and a set of colors, including width and height. The saveAsPng method is responsible for outputting the current image to the specified file.
GraphicsObject is an interface that any graphics object must use. To start using this interface, all you need to do is draw the object using the render method. It is implemented by a Line class that utilizes 4 coordinates: start and end x-values, start and end y-values. It also has a color. When render is called, this object draws a line from sx,sy to ex,ey with the color specified by the name.
The code for this library is shown in Listing 1.
List 1. Basic graphics library
<?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 ) ); } } ?> Copy after login |
The test code is shown in Listing 2:
Listing 2. Test code for basic graphics library
<?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" ); ?> Copy after login |
This test program creates a graphical environment. Then create several lines that point in different directions and have different colors. The render method can then draw them onto the graphics plane. Finally, this code saves the image as test.png.
In this article, the following command line interpreter is used to run this code, as shown below:
% php test.php % Copy after login |
Figure 2 shows what the generated test.png file looks like in Firefox.
Figure 2. Simple graphic object test

This is of course not as beautiful as the Mona Lisa, but it can meet the current work needs.
Add dimensions
Now that our first requirement—the ability to provide graphical objects—is satisfied, we can now move on to our second requirement: the ability to place one object above or below other objects using a z-value.
We can think of each z value as a face of the original image. Elements are drawn in order from smallest to largest z-value. For example, let's draw two graphic elements: a red circle and a black box. The circle has a z-value of 100, while the black box has a z-value of 200. This will place the circle behind the box, as shown in Figure 3:
Figure 3. Surfaces with different z values


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
