[ Team LiB ] Previous Section Next Section

Drawing Lines

Before you draw a line on an image, you need to determine the points from and to which you want to draw.

You can think of an image as a block of pixels indexed from 0 on both the horizontal and vertical axes. The origin is the upper-left corner of the image.

In other words, a pixel with the coordinates 5, 8 is the sixth pixel along and the ninth pixel down, looking from left to right, top to bottom.

The imageline() function draws a line between one pixel coordinate and another. It requires an image resource, four integers representing the start and end coordinates of the line, and a color resource.

Listing 15.2 adds to the image created in Listing 15.1, drawing a line from corner to corner.

Listing 15.2 Drawing a Line with imageline()
1: <?php
2: header("Content-type: image/png");
3: $image = imagecreate( 200, 200 );
4: $red = imagecolorallocate($image, 255,0,0);
5: $blue = imagecolorallocate($image, 0,0,255 );
6: imageline( $image, 0, 0, 199, 199, $blue );
7: imagepng($image);
8: ?>

We acquire two color resources, one for red (line 4) and one for blue (line 5). We then use the resource stored in the variable $blue for the line's color on line 6. Notice that our line ends at the coordinates 199, 199 and not 200, 200; that's because pixels are indexed from 0. Figure 15.2 shows the output from Listing 15.2.

Figure 15.2. Drawing a line with imageline().


    [ Team LiB ] Previous Section Next Section