Drawling A Line With Pixels In PHP

13th January 2019

From the drawers of "I didn't realise how complicated that was" I was wondering the other day how to draw a line using just pixels. This turned out to be more complicated than I thought.

Normally in PHP you would use the imageline() function to draw a line between two points. The following block of code creates and image and draws a white line from the coordinates 50x,50y to 200x,150y.

  1. // Generate image resource with a width an height of 250 pixels.
  2. $im = imagecreatetruecolor(250, 250);
  3.  
  4. // Create a color.
  5. $white = imagecolorallocate($im, 255, 255, 255);
  6.  
  7. // Draw a white line from 50x,50y to 200x,150y.
  8. imageline($im, 50, 50, 200, 150, $white);
  9.  
  10. // Write the image resource to a file called line.png.
  11. imagepng($im, 'line.png');
  12.  
  13. // Destroy the image resource.

This creates an image that looks like this.

Drawing a line in PHP.

As an exercise I was looking at how to draw the same line by just drawing the pixels along the line. The starting point to this is with the function imagesetpixel(), which allows us to set a different color to any pixel within the image. I knew that I had to step along the line and color each pixel in the line bit by bit. After a bit of research I found Bresenham's line algorithm, which allows a line to be drawn between two points. Bresenham's line algorithm is one of a family of algorithms that allow lines to be drawn between one point and another, but I'm only going to concentrate on this algorithm in this post.

Bresenham's algorithm works by looking at raster points between the start and end points. A raster point is a point at which a pixel is displayed onto the screen and because the actual line between two points will go through a number of different pixels we need to decide which pixels best describe the line. The algorithm goes along the line and decides if pixels should be 'on' or 'off', thus drawing the line.

Actually, this isn't technically true. Let's take a line going from 0x,1y to 5x,4y. What we do is run along the x values from 0 to 5 and then decide if drawing a pixel at a certain point on the y axis by looking at the gradient of the line. If the endpoint is higher then draw the pixel higher and if the endpoint is lower, draw the pixel lower. The algorithm following the following equation (taken from Wikipedia).

Bresenham's line algorithm equation

Before looping through the x coordinates we need to work out some values first.

  1. $dx = $x1 - $x0;
  2.  
  3. $dy = $y1 - $y0;
  4.  
  5. $slope = $dy / $dx;
  6.  
  7. $pitch = $y0 - $slope * $x0;

This gives us the values of 0.6 for the slope and 1 for the pitch. For each step along the x coordinate we can then work out the position of the y coordinate by using the simplified equation. 

$y = $slope * $x + $pitch;

Each point results in the following calculations. 

x Calculation to work out y y
0 0.6 * 0 + 1 1
1 0.6 * 1 + 1 2
2 0.6 * 2 + 1 2
3 0.6 * 3 + 1 3
4 0.6 * 4 + 1 3
5 n/a 4

This produces pixels in the following places (the final pixel being just drawn in at the end).

  1. .0123456
  2. 0.......
  3. 1x......
  4. 2.xx....
  5. 3...xx..
  6. 4.....x.
  7. 5.......

You might think that this is everything we need to do, but there is a problem when we try to calculate an upwards slope. The above calculations rely on the fact that the x value increases, so we need to add some code to take into account a line that starts at a high x value and decreases. We will also hit a problem if the end point is higher than the start point. We therefore need to either increment or decrement x or y in order to draw the line correctly.

I have seen examples on the internet where Bresenham's line algorithm is split into two parts where up and downward sloping lines are handled in different functions. This can be useful when highly optimising things, but generally a single function is fine.

Finally, we also need to add a tiny bit of code in case the start and end coordinates are the same as we don't need to run through any of this code.

The final code for the line drawing using Bresenham's line algorithm is as follows.

  1. /**
  2.   * Draw a line using Bresenham's line algorithm.
  3.   *
  4.   * @param resource $im
  5.   * The image resource.
  6.   * @param int $x0
  7.   * The x part of the starting coordinate.
  8.   * @param int $y0
  9.   * The y part of the starting coordinate.
  10.   * @param int $x1
  11.   * The x part of the ending coordinate.
  12.   * @param int $y1
  13.   * The y part of the ending coordinate.
  14.   * @param int $color
  15.   * The color of the line, created from imagecolorallocate().
  16.   */
  17. function drawLine($im, $x0, $y0, $x1, $y1, $color) {
  18. if ($x0 == $x1 && $y0 == $y1) {
  19. // Start and finish are the same.
  20. imagesetpixel($im, $x0, $y0, $color);
  21. return;
  22. }
  23.  
  24. $dx = $x1 - $x0;
  25. if ($dx < 0) {
  26. // x1 is lower than x0.
  27. $sx = -1;
  28. } else {
  29. // x1 is higher than x0.
  30. $sx = 1;
  31. }
  32.  
  33. $dy = $y1 - $y0;
  34. if ($dy < 0) {
  35. // y1 is lower than y0.
  36. $sy = -1;
  37. } else {
  38. // y1 is higher than y0.
  39. $sy = 1;
  40. }
  41.  
  42. if (abs($dy) < abs($dx)) {
  43. // Slope is going downwards.
  44. $slope = $dy / $dx;
  45. $pitch = $y0 - $slope * $x0;
  46.  
  47. while ($x0 != $x1) {
  48. imagesetpixel($im, $x0, round($slope * $x0 + $pitch), $color);
  49. $x0 += $sx;
  50. }
  51. } else {
  52. // Slope is going upwards.
  53. $slope = $dx / $dy;
  54. $pitch = $x0 - $slope * $y0;
  55.  
  56. while ($y0 != $y1) {
  57. imagesetpixel($im, round($slope * $y0 + $pitch), $y0, $color);
  58. $y0 += $sy;
  59. }
  60. }
  61.  
  62. // Finish by adding the final pixel.
  63. imagesetpixel($im, $x1, $y1, $color);
  64. }

Running a few examples of this function with random coordinates produces the following image.

Example of running Bresenham's line algorithm

Bresenham's line algorithm is used quite extensively in lots of different applications but it isn't that great at creating anti-aliased lines so it doesn't get used when anti-aliasing is needed.

Incidentally, the imageline() function in PHP calls the gdImageLine() function from the GD library. As can be see from the source code of gdImageLine() this function actually implements the Bresenham's line algorithm. This is more complex (and much better tested!) than my simple example here, but it still follows the same basic rules.

Comments

Permalink

curious .. have you been able to add 2 individual lines of text to an existing image?

Submitted by Kevin Brosnahan on Thu, 10/17/2019 - 14:05

Permalink

You mean using something like imagettftext()?

Submitted by philipnorton42 on Thu, 10/17/2019 - 16:50

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.