13th January 2019 - 9 minutes read time
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.
// Generate image resource with a width an height of 250 pixels.
$im = imagecreatetruecolor(250, 250);
// Create a color.
$white = imagecolorallocate($im, 255, 255, 255);
// Draw a white line from 50x,50y to 200x,150y.
imageline($im, 50, 50, 200, 150, $white);
// Write the image resource to a file called line.png.
imagepng($im, 'line.png');
// Destroy the image resource.
imagedestroy($im);
This creates an image that looks like this.