How to draw a line using imageline() function in PHP?

The imageline() function is an inbuilt function in PHP that is used to draw a line between two given points on an image resource.

Syntax

bool imageline(resource $image, int $x1, int $y1, int $x2, int $y2, int $color)

Parameters

The imageline() function takes six parameters:

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

  • $x1 − Specifies the starting x-coordinate.

  • $y1 − Specifies the starting y-coordinate.

  • $x2 − Specifies the ending x-coordinate.

  • $y2 − Specifies the ending y-coordinate.

  • $color − Specifies the line color, a color identifier created using the imagecolorallocate() function.

Return Values

The function returns True on success or False on failure.

Note: To run the following examples, you need PHP with GD extension enabled. Install using sudo apt-get install php-gd on Ubuntu or enable in php.ini on Windows.

Example 1 − Drawing a Simple Line

This example creates a blank canvas and draws a diagonal line ?

<?php
   // Create a blank image canvas
   $img = imagecreate(400, 200);
   
   // Allocate colors
   $white = imagecolorallocate($img, 255, 255, 255);
   $blue = imagecolorallocate($img, 0, 0, 255);
   
   // Set line thickness
   imagesetthickness($img, 3);
   
   // Draw a diagonal line from top-left to bottom-right
   imageline($img, 50, 50, 350, 150, $blue);
   
   // Output the image
   header('Content-type: image/png');
   imagepng($img);
   imagedestroy($img);
?>

Example 2 − Drawing Multiple Lines

This example demonstrates drawing multiple lines with different colors and thickness ?

<?php
   // Create a canvas
   $img = imagecreate(300, 300);
   
   // Allocate colors
   $white = imagecolorallocate($img, 255, 255, 255);
   $red = imagecolorallocate($img, 255, 0, 0);
   $green = imagecolorallocate($img, 0, 255, 0);
   $blue = imagecolorallocate($img, 0, 0, 255);
   
   // Draw horizontal line
   imagesetthickness($img, 2);
   imageline($img, 50, 100, 250, 100, $red);
   
   // Draw vertical line
   imagesetthickness($img, 4);
   imageline($img, 150, 50, 150, 250, $green);
   
   // Draw diagonal line
   imagesetthickness($img, 6);
   imageline($img, 50, 50, 250, 250, $blue);
   
   // Output the image
   header('Content-type: image/png');
   imagepng($img);
   imagedestroy($img);
?>

Key Points

  • Coordinates start from (0,0) at the top-left corner

  • Use imagesetthickness() to control line width

  • Colors must be allocated before use with imagecolorallocate()

  • Always call imagedestroy() to free memory

Conclusion

The imageline() function is essential for drawing lines on images in PHP. Combined with color allocation and thickness settings, it provides flexible line drawing capabilities for image manipulation tasks.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements