When working with images in PHP, we often need to draw various shapes. For drawing polygons, imageopenpolygon() and imageline() are two very practical functions. This article will explain in detail how to use them together to draw polygon borders and give a complete example.
The imageopenpolygon() function is used to draw an open polygon path, that is, draw a line connecting each vertex, but does not automatically close the last edge.
imageline() can draw a straight line between any two points, which can be used to manually close polygons .
If you need to draw a fully closed polygon border, you need to use imageopenpolygon() and then use imageline() to connect the starting point and the end point.
Here is an example of drawing pentagonal borders using the PHP GD library:
<?php
// Create a canvas
$width = 400;
$height = 400;
$image = imagecreatetruecolor($width, $height);
// Assign colors
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
// Fill the background
imagefill($image, 0, 0, $white);
// Define the vertices of a pentagon
$points = [
200, 50, // vertex1
350, 150, // vertex2
300, 300, // vertex3
100, 300, // vertex4
50, 150 // vertex5
];
// Draw open polygons
imageopenpolygon($image, $points, 5, $black);
// use imageline Manually close the last edge(vertex5回到vertex1)
imageline($image, $points[8], $points[9], $points[0], $points[1], $black);
// Output image
header('Content-Type: image/png');
imagepng($image);
// Free up resources
imagedestroy($image);
?>
imageopenpolygon() draws the line segment from vertex 1 to vertex 5, but does not connect vertex 5 back to vertex 1.
imageline() manually animates the line segment from vertex 5 to vertex 1, successfully closing the border.
After using imageopenpolygon() , remember to use imageline() to fill the last edge , otherwise the figure will be open.
Vertex coordinates need to be listed in a one-dimensional array, with each two numbers being a set of coordinates (x, y) .
Before drawing, you must ensure that the GD library is installed correctly. You can check the PHP environment information by visiting https://www.m66.net/phpinfo.php .
By combining imageopenpolygon() and imageline() , we can flexibly draw various polygon figures that require custom closing control. This method is especially useful when drawing complex graphics or dynamically generating charts. Let's try it out quickly!