Creating and Drawing Images
For now, let’s start with the simplest possible GD example. Example 9-1 is a script that generates a black filled square. The code works with any version of GD that supports the PNG image format.
<?php $im = ImageCreate(200,200); $white = ImageColorAllocate($im,0xFF,0xFF,0xFF); $black = ImageColorAllocate($im,0x00,0x00,0x00); ImageFilledRectangle($im,50,50,150,150,$black); header('Content-Type: image/png'); ImagePNG($im); ?>
Example 9-1 illustrates the basic steps in generating any image: creating the image, allocating colors, drawing the image, and then saving or sending the image. Figure 9-1 shows the output of Example 9-1.
To see the result, simply point your browser at the black.php PHP page. To embed this image in a web page, use:
<img src="black.php">
The Structure of a Graphics Program
Most dynamic image-generation programs follow the same basic steps outlined in Example 9-1.
You can create a 256-color image with the ImageCreate( )
function , which returns an image handle:
$image = ImageCreate(width
,height
);
All colors used in an image must be allocated with the ImageColorAllocate( )
function . The first color allocated becomes the background
color for the image.[*]
$color = ImageColorAllocate(image
,red
,green
,blue
);
The arguments are the numeric ...
Get Programming PHP, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.