When using PHP to process images, imageopenpolygon() is a very practical function that can draw open polygon paths (i.e., head and tail are not automatically connected). However, many friends may be puzzled when using it:
In order to figure out this problem, we have done detailed tests. Let’s take a look together below.
In PHP's GD library, imageopenpolygon() is used to draw open polygon lines. Unlike imagepolygon() , it does not automatically connect the first point and the last point.
Basic usage examples:
<?php
// Create a canvas
$image = imagecreatetruecolor(400, 400);
// Set background color to white
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
// Set the line color to blue
$blue = imagecolorallocate($image, 0, 0, 255);
// Define a point array(Clockwise)
$points = [
50, 50, // The first point
150, 50, // The second point
150, 150,// The third point
50, 150 // The fourth point
];
// Draw open polygons
imageopenpolygon($image, $points, count($points) / 2, $blue);
// Output picture
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
After running this code, you will see a U-shaped open quadrilateral, where there is no connection between the starting point and the end point .
Next we adjust the order of points to counterclockwise :
$points = [
50, 50, // The first point
50, 150, // The second point
150, 150,// The third point
150, 50 // The fourth point
];
Run again, the drawn shape is still open, except that the lines move differently .
Summary 1 :
The coordinate order does not cause the figure to close .
The coordinate order only affects the drawing order of the lines (that is, the direction of the lines will change).
If you want the figure to look closed, you need to manually add the first point to the end of the array, for example:
$points = [
50, 50,
150, 50,
150, 150,
50, 150,
50, 50 // 再加一次The first point
];
In this way, the figure drawn by imageopenpolygon() will be connected to the end, and it looks like a closed polygon!
To facilitate viewing different effects, here is a sample image address:
Clockwise example: View example
Counterclockwise example: View example
Manual closing example: View example
(If you want to generate it yourself, you can also try it with the above PHP code directly.)
imageopenpolygon() is not closed by default, regardless of coordinate order.
If you need to close, you need to add the first point at the end .
The coordinate order affects the direction of line drawing , not closed behavior.
I hope this practical explanation can help you quickly understand and master the small details of imageopenpolygon() in actual development!