Current Location: Home> Latest Articles> How to set color when using imageopenpolygon()

How to set color when using imageopenpolygon()

M66 2025-05-29

In PHP, the imageopenpolygon() function is used to draw a polygon on an image. The syntax of this function is as follows:

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

Parameter analysis:

  1. $image : The target image resource, usually created by functions such as imagecreate() or imagecreatefromjpeg() .

  2. $points : an array containing the coordinates of each point of a polygon. Each coordinate consists of two integer values ​​(x and y).

  3. $num_points : The number of vertices of a polygon.

  4. $color : The color used to draw polygons, usually created by imagecolorallocate() or imagecolorallocatealpha() functions.

How to set color parameters?

In the imageopenpolygon() function, the $color parameter determines the fill color of the polygon. If you want to set the color, you first need to use the imagecolorallocate() function to assign a color value. The format of this function is:

 int imagecolorallocate(resource $image, int $red, int $green, int $blue)

Where $image is the target image resource, $red , $green and $blue are the RGB values ​​of the color, respectively, ranging from 0 to 255. Through this function, you can set different colors.

Sample code:

 <?php
// Create a 400x400 Images
$image = imagecreate(400, 400);

// Assign colors
$bg_color = imagecolorallocate($image, 255, 255, 255); // White background
$polygon_color = imagecolorallocate($image, 0, 0, 255); // Blue polygon

// Set the vertices of the polygon
$points = array(
    100, 100,  // point 1 (x1, y1)
    300, 100,  // point 2 (x2, y2)
    350, 250,  // point 3 (x3, y3)
    250, 350,  // point 4 (x4, y4)
    150, 250   // point 5 (x5, y5)
);

// Draw polygons on images
imageopenpolygon($image, $points, count($points) / 2, $polygon_color);

// Output image
header('Content-Type: image/png');
imagepng($image);

// Destroy image resources
imagedestroy($image);
?>

Code parsing:

  1. Create image resource : Create an image of 400x400 pixels through imagecreate() .

  2. Assign colors : Use imagecolorallocate() to assign colors to the background and polygon respectively. The background is white (RGB: 255, 255, 255), and the polygon is blue (RGB: 0, 0, 255).

  3. Draw polygon : Through the imageopenpolygon() function, a polygon is drawn using the set vertex array $points and color $polygon_color .

Notes:

  • The imageopenpolygon() function does not automatically close the image resources, so the imagedestroy() function needs to be used to destroy the image and free up memory.

  • To use the transparency effect, you can use imagecolorallocatealpha() to create colors with transparency.

With the above method, you can easily draw polygons with different colors on the image.