How to draw an open polygon using the imageopenpolygon() function n PHP?

The imageopenpolygon() function is an inbuilt PHP function used to draw an open polygon on a given image. Unlike closed polygons, open polygons do not connect the last point back to the first point, creating an incomplete shape.

Syntax

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

Parameters

The imageopenpolygon() function accepts four parameters:

  • $image − Specifies the image resource to work on.

  • $points − Specifies the points of the polygon as an array of x,y coordinates.

  • $num_points − Specifies the number of points (vertices). Must be at least 3.

  • $color − Specifies the color identifier for the polygon lines.

Return Value

Returns TRUE on success or FALSE on failure.

Example 1 − Simple Triangle

This example creates a simple open triangle with three points ?

<?php
   // Create a blank image
   $img = imagecreatetruecolor(700, 300);

   // Set background color to white
   $white = imagecolorallocate($img, 255, 255, 255);
   imagefill($img, 0, 0, $white);

   // Allocate green color for the polygon
   $col_poly = imagecolorallocate($img, 0, 255, 0);

   // Draw the open polygon (triangle)
   imageopenpolygon($img, array(
      50, 50,    // Point 1 (x1, y1)
      150, 200,  // Point 2 (x2, y2)
      400, 200   // Point 3 (x3, y3)
   ), 3, $col_poly);

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

Example 2 − Six-Point Polygon

This example demonstrates a more complex open polygon with six vertices ?

<?php
   // Create a blank image
   $image = imagecreatetruecolor(700, 300);
   
   // Set white background
   $white = imagecolorallocate($image, 255, 255, 255);
   imagefill($image, 0, 0, $white);
   
   // Allocate blue color
   $blue = imagecolorallocate($image, 0, 100, 255);

   // Six points array (x1,y1, x2,y2, x3,y3, x4,y4, x5,y5, x6,y6)
   $points = array(
      60, 130,   // Point 1
      130, 230,  // Point 2
      280, 230,  // Point 3
      350, 130,  // Point 4
      280, 50,   // Point 5
      130, 50    // Point 6
   );
   
   // Create the open polygon
   imageopenpolygon($image, $points, 6, $blue);

   // Output to browser
   header('Content-type: image/png');
   imagepng($image);
   imagedestroy($image);
?>

Key Differences

The main difference between imageopenpolygon() and imagepolygon() is that open polygons do not draw a line connecting the last point back to the first point, while closed polygons create a complete enclosed shape.

Conclusion

The imageopenpolygon() function is useful for creating geometric shapes that don't need to be closed. Remember to set a background color for better visibility and always destroy the image resource to free memory.

Updated on: 2026-03-15T09:49:19+05:30

446 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements