1. Home
  2. Computing & Technology
  3. PHP / MySQL

GD Library - The Basics of Drawing with PHP

By Angela Bradley, About.com

2 of 7

Rectangle With Text

Image created with GD Library

Our code creates this image.

<?php
header ("Content-type: image/png");
$handle = ImageCreate (130, 50) or die ("Cannot Create image");
$bg_color = ImageColorAllocate ($handle, 255, 0, 0);
$txt_color = ImageColorAllocate ($handle, 0, 0, 0);
ImageString ($handle, 5, 5, 18, "PHP.About.com", $txt_color);
ImagePng ($handle);
?>
  1. With this code we are creating a PNG image. In our first line, the header, we set the content type. If we were creating a jpg or gif image, this would change accordingly.

  2. Next we have the image handle. The two variables in ImageCreate () are the width and height of our rectangle, in that order. Our rectangle is 130 pixels wide, and 50 pixels high.

  3. Next we set our background color. We use ImageColorAllocate () and have four parameters. The first is our handle, and the next three determine the color. They are the Red, Green and Blue values (in that order) and must be an integer between 0 and 255. This website gives you the integers for basic web colors if you are not familiar with choosing colors in this format. In our example we have chosen red.

  4. Next we choose our text color, using the same format as our background color. We have chosen black.

  5. Now we enter the text we want to appear in our graphic using ImageString (). The first parameter is the handle. Then the font (1-5), starting X ordinate, starting Y ordinate, the text itself, and finally it's color.

  6. Finally ImagePng () actually creates the PNG image.

2 of 7

Explore PHP / MySQL

More from About.com

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. Graphics- GD Library
  5. GD Library - PHP GD Library - GD Image Library

©2008 About.com, a part of The New York Times Company.

All rights reserved.