Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Points and Lines

Drawing points is accomplished with the function imagesetpixel(), which takes four parameters: the image to draw on, the X and Y coordinates, and the color to use. Thus, you can use it like this:

    $width = 255;
    $height = 255;
    $image = imagecreatetruecolor($width, $height);

    for ($i = 0; $i <= $width; ++$i) {
            for ($j = 0; $j <= $height; ++$j) {
                    $col = imagecolorallocate($image, 255, $i, $j);
                    imagesetpixel($image, $i, $j, $col);
            }
    }

    header("Content-type: image/png");
    imagepng($image);
    imagedestroy($image);

In that example, there are two loops to handle setting the green and blue parameters with imagecolorallocate(), with red always being set to 255. This color is then used to set the relevant pixel to the newly allocated color, which should give you a smooth gradient like the one in Figure 16-23.

Smooth gradiants using per-pixel coloring

Figure 16-23. Smooth gradiants using per-pixel coloring

Drawing lines is only a little more difficult than individual pixels, and is handled by the imageline() function. This time, the parameters are the image to draw on, the X and Y coordinates of the start of the line, the X and Y coordinates of the end of the line, and the color to use for drawing. We can extend our pixel script to draw a grid over the gradient by looping from 0 to $width and $height, incrementing by 15 each time, and drawing a line at the appropriate place. $width and $height were both set to 241 in the previous ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page