Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
imagepolygon() function in PHP
The imagepolygon() function is used to draw a polygon on an image resource in PHP. This function is part of the GD library extension and allows you to create polygons with any number of vertices.
Syntax
bool imagepolygon(resource $image, array $points, int $num_points, int $color)
Parameters
- $image − An image resource created with imagecreatetruecolor() or similar functions.
- $points − An array containing the x and y coordinates of the polygon's vertices in sequential order.
- $num_points − The total number of vertices (points) in the polygon.
- $color − A color identifier created with imagecolorallocate() function.
Return Value
The imagepolygon() function returns TRUE on success or FALSE on failure.
Example
The following example demonstrates how to create a triangle using imagepolygon() −
<?php
$img = imagecreatetruecolor(400, 300);
$color = imagecolorallocate($img, 120, 160, 190);
$bgcolor = imagecolorallocate($img, 10, 100, 50);
imagefill($img, 0, 0, $bgcolor);
imagepolygon($img, array(
50, 50, // Point 1: x=50, y=50
150, 200, // Point 2: x=150, y=200
340, 200 // Point 3: x=340, y=200
),
3,
$color);
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
?>
Output
The above code generates a triangle on a dark green background. The polygon is drawn with light blue color connecting the three specified vertices.
Key Points
- The points array must contain an even number of elements (x,y coordinates).
- The polygon is automatically closed by connecting the last point to the first.
- Requires the GD extension to be enabled in PHP.
- Use imagedestroy() to free memory after image processing.
Conclusion
The imagepolygon() function provides an easy way to draw polygons of any shape on PHP-generated images. It's particularly useful for creating geometric shapes, charts, and custom graphics in web applications.
