PHP Graphics
Introduction
With the assistance of the GD library, you can use PHP to create applications that use dynamic images to display stock quotes, reveal poll results, monitor system performance, and even create games. However, it’s not like using Photoshop or GIMP; you can’t draw a line by moving your mouse. Instead, you need to precisely specify a shape’s type, size, and position.
GD has an existing API, and PHP tries to follows its syntax and function-naming conventions. So if you’re familiar with GD from other languages, such as C or Perl, you can easily use GD with PHP. If GD is new to you, it may take a few minutes to figure it out, but soon you’ll be drawing like Picasso.
The feature set of GD varies greatly depending on which version of GD you’re running and which features were enabled during configuration. GD can support GIFs, JPEGs, PNGs, and WBMPs. GD reads in PNGs and JPEGs with almost no loss in quality. Also, GD supports PNG alpha channels, which allow you to specify a transparency level for each pixel.
Besides supporting multiple file formats, GD lets you draw pixels, lines, rectangles, polygons, arcs, ellipses, and circles in any color you want. Covers straight shapes, and Covers the curved ones. To fill shapes with a pattern instead of a solid color.
You can also draw text using a variety of font types, including built-in and TrueType fonts. Shows the ins and outs of the three main text-drawing functions, and Shows how to center text within a canvas. These two recipes form the basis, which combines an image template with real-time data to create dynamic images. GD also lets you make transparent GIFs and PNGs. Setting a color as transparent and using transparencies in patterns.
Beyond creating new images, you can work with existing images. For example, add a watermark to identify yourself by overlaying text or an image on top of the picture. This is the subject. Generating thumbnail images is covered, which shows how to create scaled-down versions of larger images. To extract image metadata from digital photos and other images that store information using the EXIF standard.
Moves away from GD and shows how to securely serve images by restricting user access. Last, there’s an example application taking poll results and producing a dynamic bar graph showing what percentage of users voted for each answer.
GD is bundled with PHP. The GD section of the online PHP Manual also lists the location of the additional libraries necessary to provide support for additional graphics formats, such as JPEG and PNG, and fonts, such as TrueType.
There are two easy ways to see which version, if any, of GD is installed on your server and how it’s configured. One way is to call phpinfo(). You should see --with-gd at the top under Configure Command; further down the page there is also a section titled gd that has more information about which version of GD is installed and what features are enabled.
The other option is to check the return value of function_exists('image create'). If it returns true, GD is installed. The imagetypes() function returns a bit field indicating which graphics formats are available. See PHP’s website for more on how to use this function. If you want to use a feature that isn’t enabled, you need to rebuild PHP yourself or get your ISP to do so.
The basic image-generation process has three steps: creating the image, adding graphics and text to the canvas, and displaying or saving the image. For example:
$image = ImageCreateTrueColor(200, 50); // defaults to black
// color the background grey
$grey = 0xCCCCCC;
ImageFilledRectangle($image, 0, 0, 200 - 1, 50 - 1, $grey);
// draw a white rectangle on top
$white = 0xFFFFFF;
ImageFilledRectangle($image, 50, 10, 150, 40, $white);
// send it as PNG
header('Content-type: image/png');
ImagePNG($image);
ImageDestroy($image);
The output of this code, which prints a white rectangle on a grey background.
Figure A white rectangle on a grey background
To begin, you create an image canvas. The ImageCreateTrueColor() function doesn’t return an actual image. Instead, it provides you with a handle to an image; it’s not an actual graphic until you specifically tell PHP to write the image out. Using ImageCreateTrueColor(), you can juggle multiple images at the same time.
The parameters passed to ImageCreateTrueColor() are the width and height of the graphic in pixels. In this case, it’s 200 pixels across and 50 pixels high. The default background color for new canvases is black.
In addition to creating a new image, you can also edit existing images. To open a graphic, call ImageCreateFromPNG() or a similarly named function (such as ImageCreateFrom GIF(), ImageCreateFromJPEG(), ImageCreateFromWBMP(), …) to open a different file format. The filename is the only argument, and files can live locally or on remote servers:
// open a PNG from the local machine
$graph = ImageCreateFromPNG('/path/to/graph.png');
// open a JPEG from a remote server
$icon = ImageCreateFromJPEG('http://www.example.com/images/icon.jpeg');
Call ImageFilledRectangle() to place a box onto the canvas. ImageFilledRectangle() takes many parameters: the image to draw on, the x and y coordinates of the upper-left corner of the rectangle, the x and y coordinates of the lower-right corner of the rectangle, and finally, the color to use to draw the shape.
The color is a number representing its RGB values, similar to how you do it with HTML and CSS. For example, the HTML hex code for white is #FFFFFF. In PHP, you write this in hex as 0xFFFFFF (or you can use the decimal value, which is 16777215).
Another option is to use the ImageAllocate() function, which takes a canvas, and the red, green, and blue values:
$color = ImageAllocate($image, $r, $g, $b);
// For example, white
$white = ImageAllocate($image, 0xFF, 0xFF, 0xFF); // hex
$white = ImageAllocate($image, 255, 255, 255); // decimal
// Or...
$grey = ImageColorAllocate($image, 204, 204, 204);
$orange = ImageColorAllocate($image, 0xE9, 0x52, 0x22);
To paint over the default background color of black, allocate a color and then put a filled rectangle on the canvas. Because canvases begin at (0,0), use those for the first set of x and y coordinates. Then subtract one from the height and width dimensions for the second set of x and y coordinates:
// color the background grey
$grey = 0xCCCCCC;
ImageFilledRectangle($image, 0, 0, 200 - 1, 50 - 1, $grey);
Then you can begin drawing other items. For example, to draw a rectangle on $image, starting at (50,10) and going to (150,40), in the color white:
// draw a white rectangle on top
$white = 0xFFFFFF;
ImageFilledRectangle($image, 50, 10, 150, 40, $white);
Unlike what you might expect, (0,0) is in the upper-left corner. Therefore, as you move down the canvas, the coordinates become larger. For example, in a 50-pixel-high canvas, the vertical coordinate of a spot 10 pixels from the top of canvas is 10. It’s neither 40 nor −10.
Now that the image is all ready to go, you can serve it up. First, send a Content-Type header to let the browser know what type of image you’re sending. In this case, display a PNG. Next, have PHP write the PNG image out using ImagePNG():
header('Content-type: image/png');
ImagePNG($image);
To write the image to disk instead of sending it to the browser, provide a second argument to ImagePNG() with where to save the file:
ImagePNG($image, '/path/to/your/new/image.png');
Because the file isn’t going to the browser, there’s no need to call header(). Make sure to specify a path and an image name, and be sure PHP has permission to write to that location.
PHP cleans up the image when the script ends, but to manually deallocate the memory used by the image, call ImageDestroy($image) and PHP immediately gets rid of it:
ImageDestroy($image);
No comments:
Post a Comment