How to Draw Lines On An Image

Before we begin drawing on our image, there are two functions that we should consider, for added variety.

1. Line color can be modified using the imagecolorallocate() function, which we learned about before. It should be stored in a variable to be used later.

2. Line thickness can be modified using the imagesetthickness() function, which requires two parameters: imagesetthickness(image, thickness)

The imageline() function itself requires 6 parameters. The syntax is: imageline(image, x1, y1, x2, y2, color)

  • image = Refers to the Image Resource That the Line Will Be Applied to
  • x1 = x-coordinate For First Point
  • y1 = y-coordinate For First Point
  • x2 = x-coordinate For Second Point
  • y2 = y-coordinate For Second Point
  • color = Refers to the Line Color Identifier Created With imagecolorallocate()

<?php
header('Content-type: image/png');
$png_image = imagecreate(150, 150);
imagecolorallocate($png_image, 15, 142, 210);
$black = imagecolorallocate($png_image, 0, 0, 0);
imageline($png_image, 0, 0, 150, 150, $black);
imagepng($png_image);
imagedestroy($png_image);
?>

Guess what the program above will do? It will draw a diagonal black line from the top left to the bottom right of the image.

Now, can you figure out how to draw a thick black border around the entire image? That might be more of a challenge…

<?php
header('Content-type: image/png');
$png_image = imagecreate(150, 150);

imagecolorallocate($png_image, 15, 142, 210);
imagesetthickness($png_image, 5);
$black = imagecolorallocate($png_image, 0, 0, 0);

$x = 0;
$y = 0;
$w = imagesx($png_image) - 1;
$z = imagesy($png_image) - 1;

imageline($png_image, $x, $y, $x, $y+$z, $black);
imageline($png_image, $x, $y, $x+$w, $y, $black);
imageline($png_image, $x+$w, $y, $x+$w, $y+$z, $black);
imageline($png_image, $x, $y+$z, $x+$w ,$y+$z, $black);

imagepng($png_image);
imagedestroy($png_image);
?>

To draw dashed lines, use the following function and syntax: imagedashedline(image, x1, y1, x2, y2, color)

<?php
header('Content-type: image/png');
$png_image = imagecreate(150, 150);

imagecolorallocate($png_image, 15, 142, 210);
imagesetthickness($png_image, 5);
$black = imagecolorallocate($png_image, 0, 0, 0);

$x = 0;
$y = 0;
$w = imagesx($png_image) - 1;
$z = imagesy($png_image) - 1;

imageline($png_image, $x, $y, $x, $y+$z, $black);
imageline($png_image, $x, $y, $x+$w, $y, $black);
imageline($png_image, $x+$w, $y, $x+$w, $y+$z, $black);
imageline($png_image, $x, $y+$z, $x+$w ,$y+$z, $black);

imagedashedline($png_image, 150, 0, 0, 150, $black);

imagepng($png_image);
imagedestroy($png_image);
?>

Summary:

Function Description
imagecolorallocate() Allocate a Color For An Image
imagesetthickness() Set the Thickness For Line Drawing
imageline() Draw a Line
imagedashedline() Draw a Dashed Line

Comments