Current Location: Home> Latest Articles> How to Draw a Line in PHP – Using GD Library for Graphic Rendering

How to Draw a Line in PHP – Using GD Library for Graphic Rendering

M66 2025-07-14

Steps to Draw a Line in PHP

1. Create a Canvas

First, we need to create a canvas using the imagecreatetruecolor function provided by the GD library. You can define the width and height of the canvas based on your needs.

<?php
$im = imagecreatetruecolor(500, 500);

2. Set the Color

Next, use the imagecolorallocate function to set the color. You can define the color using RGB values, where the red, green, and blue components range from 0 to 255.

<?php
$blue = imagecolorallocate($im, 0, 0, 255);

3. Draw the Line

After setting up the canvas and color, you can draw the line using the imageline function. This function accepts the starting (x1, y1) and ending (x2, y2) coordinates, as well as the color of the line.

<?php
imageline($im, 100, 100, 400, 400, $blue);

4. Output the Image

Once the line is drawn, you can output the image using the imagepng function. Remember to set the appropriate Content-Type using the header function.

<?php
header('Content-Type: image/png');
imagepng($im);

5. Destroy the Resource

After outputting the image, it’s important to free the image resource to prevent memory leaks.

<?php
imagedestroy($im);

Full Code Example:

<?php
// Create a 500x500 canvas
$im = imagecreatetruecolor(500, 500);

// Allocate blue color
$blue = imagecolorallocate($im, 0, 0, 255);

// Draw a blue line from (100, 100) to (400, 400)
imageline($im, 100, 100, 400, 400, $blue);

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

// Destroy the resource
imagedestroy($im);
?>

Tips:

  • Make sure the values of x1, y1, x2, and y2 are within the canvas range.
  • You can use the imagedashedline() function to draw dashed lines.
  • Use the imagecolortransparent() function to set a transparent background.
  • You can use imagefilledpolygon() to draw filled shapes.
  • Use imagestring() to draw text on the image.

Conclusion

By following these steps, you can easily draw a line in PHP and explore more advanced graphic rendering techniques with the GD library. This opens up many possibilities for creating dynamic and engaging visual effects for your website.