Current Location: Home> Latest Articles> How to Convert SVG Paths to Coordinate Arrays Recognized by imageopenpolygon() Function

How to Convert SVG Paths to Coordinate Arrays Recognized by imageopenpolygon() Function

M66 2025-06-12

When working with images in PHP, the imageopenpolygon() function is a very useful tool that can draw a polygon based on a set of points. However, if your source data is an SVG path (the d attribute), you first need to parse the SVG path into a format recognized by imageopenpolygon(): a simple coordinate array. This article will guide you step by step through the conversion process.

Understanding the Differences Between SVG Paths and imageopenpolygon()

  • SVG Path (d attribute): Typically a string, such as:

    M 10 10 L 100 10 L 100 100 L 10 100 Z  
    

    Where M stands for "move to", L stands for "line to", and Z stands for "close path".

  • imageopenpolygon(): Requires a one-dimensional array in the format: [x1, y1, x2, y2, ..., xn, yn].

Therefore, our goal is to translate the commands in the SVG path into this array format.

Step 1: Extract Coordinates from the SVG Path

First, we need to parse the d attribute string of the SVG to extract all the useful coordinates. This can be done using simple regular expression matching.

function parseSvgPathToPoints($svgPath) {  
    $commands = preg_split('/(?=[MLZmlz])/', $svgPath, -1, PREG_SPLIT_NO_EMPTY);  
    $points = [];  
    $type = strtoupper(substr(trim($command), 0, 1));  
    $coords = trim(substr(trim($command), 1));  

    if ($type === 'M' || $type === 'L') {  
        $pairs = preg_split('/[\s,]+/', $coords);  
        for ($i = 0; $i < count($pairs) - 1; $i += 2) {  
            $x = (float)$pairs[$i];  
            $y = (float)$pairs[$i + 1];  
            $points[] = $x;  
            $points[] = $y;  
        }  
    } elseif ($type === 'Z') {  
        // 'Z' indicates a closed path, you can optionally handle it (for example, by copying the start point to the end)  
    }  
}  

return $points;  

}

Tip:

If your SVG path includes complex commands like C (curves), this simple parser does not support them. Here, we are mainly handling basic commands like M, L, and Z.

Step 2: Draw with imageopenpolygon()

Once you have the converted coordinate array, drawing the polygon becomes very simple.

// Example SVG path  
$svgPath = 'M 10 10 L 100 10 L 100 100 L 10 100 Z';  
<p>// Parse the path<br>
$points = parseSvgPathToPoints($svgPath);</p>
<p>// Create the image<br>
$image = imagecreatetruecolor(200, 200);<br>
$white = imagecolorallocate($image, 255, 255, 255);<br>
$black = imagecolorallocate($image, 0, 0, 0);</p>
<p>imagefill($image, 0, 0, $white);</p>
<p>// Draw the polygon<br>
imageopenpolygon($image, $points, count($points) / 2, $black);</p>
<p>// Output the image<br>
header('Content-Type: image/png');<br>
imagepng($image);<br>
imagedestroy($image);<br>

When you visit this PHP file, it will display the drawn polygon image directly. If you want to save the file instead of outputting it, you can replace imagepng($image, 'your_path.png').

Step 3: Handling More Complex Scenarios

If you have a more complex SVG file (such as an icon set downloaded from m66.net), you may need to:

  • Support relative commands (lowercase m/l)

  • Support curves (C/Q)

  • Support compound paths For these, you will need a more powerful SVG parser, such as the SVGPathData PHP Library (the example link uses the m66.net domain).

Of course, if your needs are limited to parsing basic shapes, the simple regex approach above should suffice.

Conclusion

Converting an SVG path to the format required by imageopenpolygon() is fundamentally about:

  1. Splitting the SVG string by commands;

  2. Extracting each pair of coordinates;

  3. Assembling them into a one-dimensional array required by PHP.

By mastering this process, you can easily implement SVG-to-image drawing in PHP!