Approaches to Web Development for Bioinformatics

Previous  Contents  Next
References

Image Generation

PHP scripts can generate images using the GD library. This is a built in extension but is not enabled by default. To enable it in the make sure the line


PHP Configuration File

extension=php_gd2.dll

or equivalent unix shared library is present in the php.ini file. The PHP manual 35 gives details on the use of the GD library with PHP. The PHP functions wrap the C-based GD library. More information on the GD project can be found at the libgd site 71.

Here is a program that creates a simple rectangle and then outputs it to the browser as a PNG image.


PHP

<?php
// Program to demonstrate use of GD graphics library

// Create a rectangle
$image = ImageCreate(200, 100);
$backgroundColor = ImageColorAllocate($image, 255, 255, 255);
$red = ImageColorAllocate($image, 255, 0, 0);
ImageFilledRectangle($image, 50, 50, 150, 100, $red);

// Output the image
header('Content-Type: image/png');
ImagePNG($image);
?>

The program first creates an image object with the ImageCreate($width, $height) call. Then it allocates objects for the colors white and red with the function ImageColorAllocate($image, $r, $g, $b). A red rectangle is drawn on the image with the call ImageFilledRectangle($image, $x1, $y1, $x2, $y2, $color). All the units are pixels and the coordinate origin is at the top left. A header is written to let the browswer know to expect a PNG MIME type. Finally, the image is written to the browswer with the call ImagePNG($image). The image generated looks like this.

Screenshot of Basic PHP Image Generation Script for Script Above

Open rectangles can be drawn with the ImageRectangle($image, $x1, $y1, $x2, $y2, $color) function and lines can be drawn with the function ImageLine($image, $x1, $y1, $x2, $y2, $color). This is demonstrated in the script test_gd_line.phps. The program output is shown below:

Screenshot of Basic PHP Image Generation Script
(test_gd_line.phps)

You can draw text on images with the ImageString($image, $fontSize, $x, $y, $text, $color) function. The program test_gd_text.phps demonstrates this. The image generated is shown below.

Screenshot of Basic PHP Image Generation Script
(test_gd_text.phps)

Previous  Contents  Next
References

Contributed Comments and NotesAdd a comment.

There are no user comments.

Google

Please send ideas and opinions by email at alexamies@gmail.com.

© 2006-2007 Alex Amies