Setting Individual Pixels


Want more graphics control? You can set individual pixels using the imagesetpixel method:

 imagesetpixel(resource image, int x, int y, int color) 

As you'd expect, this function draws a pixel at x, y in image image of color color. When you're drawing graphics, working pixel-by-pixel is usually too slow. But you can generally get away with drawing extensive pixel graphics on the server because the extra few seconds usually aren't noticedthe Internet is slow enough anyway.

For example, say you wanted to draw a dotted line, which you can do with imagesetpixel. You can use a for loop, as here, where we're drawing one pixel and then skipping three pixels before drawing the next pixel:

 $image_height = 100; $image_width = 300; $image = imagecreate($image_width, $image_height); $back_color = imagecolorallocate($image, 200, 200, 200); $drawing_color = imagecolorallocate($image, 0, 0, 0); for($loop_index = 20; $loop_index < 280; $loop_index += 3){          .          .          . } 

All that's left is to use imagesetpixels to actually draw the individual pixels inside the for loop that we've just set up, as you can see in phppixels.php, Example 8.

Example 8. Drawing pixels, phppixels.php
 <?php     $image_height = 100;     $image_width = 300;     $image = imagecreate($image_width, $image_height);     $back_color = imagecolorallocate($image, 200, 200, 200);     $drawing_color = imagecolorallocate($image, 0, 0, 0);     for($loop_index = 20; $loop_index < 280; $loop_index += 3){         imagesetpixel($image, $loop_index, 50, $drawing_color);     }     header("Content-type: image/jpeg");     imagejpeg($image);     imagedestroy($image); ?> 

We'll embed phppixels.php in a web page, phppixels.html:

 <HTML>     <HEAD>         <TITLE>Drawing individual pixels</TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Drawing individual pixels             </H1>             <BR>             <IMG src="/books/1/265/1/html/2/phppixels.php">         </CENTER>     </BODY> </HTML> 

You can see the results in Figure 9, where the line we're drawing is indeed dotted, thanks to the for loop we've used.

Figure 9. Drawing individual pixels.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net