Cover Image for PHP imagepolygon() Function
178 views

PHP imagepolygon() Function

As of my last update in September 2021, the imagepolygon() function in PHP is used to draw a filled polygon on an image using the GD Graphics Library. GD is a PHP extension that allows you to create and manipulate images in various formats, such as PNG, JPEG, and GIF.

Here’s the syntax of the imagepolygon() function:

bool imagepolygon ( resource $image , array $points , int $num_points , int $color )

Parameters:

  • $image: A GD image resource created with functions like imagecreatetruecolor() or imagecreatefromjpeg().
  • $points: An array of points defining the vertices of the polygon. The array should be in the format [x1, y1, x2, y2, ..., xn, yn].
  • $num_points: The number of points in the polygon. It should be half the size of the $points array since each point consists of an x and y coordinate.
  • $color: The color of the polygon, specified using imagecolorallocate() or imagecolorallocatealpha().

Return value:

  • Returns true on success, or false on failure.

Example:

// Create a blank image
$image = imagecreatetruecolor(400, 400);

// Allocate colors
$background = imagecolorallocate($image, 255, 255, 255); // White background
$blue = imagecolorallocate($image, 0, 0, 255); // Blue color

// Set the background color
imagefill($image, 0, 0, $background);

// Define the points for the polygon
$points = [100, 50, 300, 50, 250, 250, 150, 250];

// Draw a filled polygon
imagepolygon($image, $points, count($points) / 2, $blue);

// Output the image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

In this example, a blank image is created using imagecreatetruecolor(), and a white background is set using imagefill(). Then, a blue filled polygon is drawn on the image using the imagepolygon() function with the specified points.

Please note that the GD Graphics Library requires the GD extension to be enabled in your PHP configuration. Additionally, always remember to use proper error handling to deal with potential errors that may occur during image creation and manipulation.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS