Drawing squares, rectangles, circles, ellipses and polygons are all fairly simple using PHP's GD Library functions.
First, let's create a 300px by 300px image, allocate two different colors (grey and green), fill up the image with the grey color, send it to the browser, and clear the memory:
<?php
header('Content-type: image/png');
$png_image = imagecreate(300, 300);
$grey = imagecolorallocate($png_image, 199, 199, 199);
$green = imagecolorallocate($png_image, 128, 204, 204);
imagefilltoborder($png_image, 0, 0, $grey, $grey);
imagepng($png_image);
imagedestroy($png_image);
?>
Now, let's explore the 3 functions that we can use to make some basic shapes on our image:
Use the imagefilledrectangle() function to draw squares and rectangles, specifying the top left and bottom right corner positions.
imagefilledrectangle (resource $image, int $x1, int $y1, int $x2, int $y2, int $color)
Use the imagefilledellipse() function to draw circles and ellipses, specifying the center position, width and height of the shape.
imagefilledellipse (resource $image, int $cx, int $cy, int $width, int $height, int $color)
Use the imagefilledpolygon() function to draw polygons, specifying the three point of the shape.
imagefilledpolygon (resource $image, array $points, int $num_points, int $color)
Each function requires several parameters, first identifying the image to draw on, then identifying the size and/or position of the object being drawn, and finally specifying the color that the object should be drawn in.
Let's look at an example of the code:
<?php
header('Content-type: image/png');
$png_image = imagecreate(300, 300);
$grey = imagecolorallocate($png_image, 229, 229, 229);
$green = imagecolorallocate($png_image, 128, 204, 204);
imagefilltoborder($png_image, 0, 0, $grey, $grey);
imagefilledrectangle ($png_image, 20, 20, 80, 80, $green); // SQUARE
imagefilledrectangle ($png_image, 100, 20, 280, 80, $green); // RECTANGLE
imagefilledellipse ($png_image, 50, 150, 75, 75, $green); // CIRCLE
imagefilledellipse ($png_image, 200, 150, 150, 75, $green); // ELLIPSE
$poly_points = array(150, 200, 100, 280, 200, 280);
imagefilledpolygon ($png_image, $poly_points, 3, $green); // POLYGON
imagepng($png_image);
imagedestroy($png_image);
The above code will produce this result.
The best way to learn is to experiment, so try changing some of the numbers in the example and see what happens!
Use the imageellipse(), imagepolygon() and imagerectangle() functions to draw shapes that are not filled in with color.
Summary:
Function | Description |
---|---|
imagefilledellipse() | Draws a Filled Ellipse |
imageellipse() | Draws An Ellipse |
imagefilledpolygon() | Draws a Filled Polygon |
imagepolygon() | Draws a Polygon |
imagefilledrectangle() | Draws a Filled Rectangle |
imagerectangle() | Draws a Rectangle |