imagedashedline() function in PHP

The imagedashedline() function in PHP draws a dashed line on an image resource. This function is part of the GD library and creates a line with alternating filled and empty segments between two specified points.

Syntax

imagedashedline($image, $x1, $y1, $x2, $y2, $color)

Parameters

  • image − An image resource created by functions like imagecreatetruecolor()

  • x1 − Starting point x-coordinate

  • y1 − Starting point y-coordinate

  • x2 − Ending point x-coordinate

  • y2 − Ending point y-coordinate

  • color − Line color created with imagecolorallocate()

Return Value

Returns TRUE on success or FALSE on failure.

Example

Here's how to create an image with a dashed line ?

<?php
    // Create a 500x370 image
    $image = imagecreatetruecolor(500, 370);
    
    // Set background color (dark blue-gray)
    $bgcolor = imagecolorallocate($image, 70, 90, 120);
    imagefill($image, 0, 0, $bgcolor);
    
    // Set line color (light green)
    $color = imagecolorallocate($image, 90, 220, 175);
    
    // Draw dashed line from (0,0) to (150,50)
    imagedashedline($image, 0, 0, 150, 50, $color);
    
    // Output as PNG image
    header("Content-type: image/png");
    imagepng($image);
    
    // Clean up memory
    imagedestroy($image);
?>

Multiple Dashed Lines Example

You can draw multiple dashed lines on the same image ?

<?php
    $image = imagecreatetruecolor(400, 300);
    $bgcolor = imagecolorallocate($image, 255, 255, 255);
    imagefill($image, 0, 0, $bgcolor);
    
    // Different colored dashed lines
    $red = imagecolorallocate($image, 255, 0, 0);
    $blue = imagecolorallocate($image, 0, 0, 255);
    $green = imagecolorallocate($image, 0, 255, 0);
    
    // Draw horizontal, vertical, and diagonal dashed lines
    imagedashedline($image, 50, 100, 350, 100, $red);    // Horizontal
    imagedashedline($image, 200, 50, 200, 250, $blue);   // Vertical
    imagedashedline($image, 50, 50, 350, 250, $green);   // Diagonal
    
    header("Content-type: image/png");
    imagepng($image);
    imagedestroy($image);
?>

Key Points

  • The function creates a dashed pattern automatically − you cannot customize dash length

  • Coordinates are in pixels, with (0,0) at the top-left corner

  • Always call imagedestroy() to free memory after image processing

  • This function is deprecated as of PHP 5.0.0 − use imagesetstyle() with imageline() for more control

Conclusion

The imagedashedline() function provides a simple way to draw dashed lines on images. While deprecated, it still works for basic dashed line requirements in image generation tasks.

Updated on: 2026-03-15T07:47:28+05:30

137 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements