GD Library - Draw Graphical Elements

This section provides a tutorial example on how to draw graphical elements using GD Library functions.

You can use GD Library functions to create a new image and draw some graphical elements.

1. Write a PHP script to create an image with some graphical elements added and save it to GD-Graphics.png:

<?php
#  GD-Create-Image.php
#- Copyright 2009 (c) HerongYang.com. All Rights Reserved.

$image = imagecreatetruecolor(400,400);

$blue = imagecolorallocate($image, 0, 0, 255);
$green = imagecolorallocate($image, 0, 255, 0);
$red = imagecolorallocate($image, 255, 0, 0);

print("Drawing a box...\n");
imagefilledrectangle($image, 50, 50, 350, 350, $blue);

print("Drawing a circle...\n");
imagefilledellipse($image, 200, 200, 200, 200, $green);

print("Drawing 2 lines...\n");
imageline($image, 0,0, 400, 400, $red);
imageline($image, 400,0, 0, 400, $red);

$file = "GD-Graphics.png";
imagepng($image, $file);
print("Image saved:\n");
print("   File: $file\n");
?>

2. Run the above script:

herong$ php GD-Create-Image.php
Drawing a box...
Drawing a circle...
Drawing 2 lines...
Image saved:
   File: GD-Graphics.png

3. View GD-Graphics.png. You see a nice image.

Table of Contents

 About This Book

 Introduction and Installation of PHP

 Managing PHP Environment and Modules on macOS

 Managing PHP Environment and Modules on CentOS

 Configuration and Modules

 cURL Module - Client for URL

 DOM Module - Parsing HTML Documents

GD Module - Manipulating Images and Pictures

 GD Library of Image Functions

GD Library - Draw Graphical Elements

 GD Library - Print 2 Pictures on 1 Page

 GD Library - Create Transparent Image

 Transparent Image Over Text Web Page

 GD Library - Pad Transparent Image

 MySQLi Module - Accessing MySQL Server

 OpenSSL Module - Cryptography and SSL/TLS Toolkit

 PCRE Module - Perl Compatible Regular Expressions

 SOAP Module - Creating and Calling Web Services

 SOAP Module - Server Functions and Examples

 Zip Module - Managing ZIP Archive Files

 References

 Index

 Full Version in PDF/EPUB