Skip to main content

Image Generation Using PHP

Image Generation Using PHP

In one of the previous posts about CAPTCHA Image Generation we made use of PHP’s image generation functions but didn’t discuss about them. So, if you had any problems or just want to know more, read on.

Creating and outputting images from PHP is very simple and easy. And since PHP supports images in a number of different formats you can very easily generate images in various formats such as JPEG, PNG, GIF etc. Generating  images involves the following steps:

  1. Creating a canvas.

  2. Drawing

  3. Outputting the image.

Now, let’s look at each of the steps in detail.

Creating a Canvas

Creating a canvas is very easy, just use the following function:

resource ImageCreateTrueColor int $width int $height )

The capitalization doesn’t matter as with any function in PHP.

If you want your canvas to have some background color (default is black) you can use the following function:

bool ImageFill resource $image int $x int $y int $color )

Where color is to be first allocate using the following function:

int ImageColorAllocate resource $image int $red int $green int $blue )

You can also use an existing image as base canvas for your new image, in that case create your image using the following function:

resource ImageCreateFromJPEG string $filename )

Images in other format can also be used, for PNG →  ImageCreateFromPNG (), GIF → ImageCreateFromGIF ().


After having set up the canvas, let’s draw something on it, say, a rectangle. The rectangle drawing function with its argument list is:

bool ImageRectangle resource $image int $x1 int $y1 int $x2 int $y2 int $color )

For allocating color use the ImageColorAllocate() function.

The following will create a square of size 10px X 10px having a blue border:

$img ImageCreateTrueColor(20, 20);
$blue ImageColorAllocate($img00255);
ImageRectangle($img, 0, 0, 10, 10$blue);

You can browse the complete list of drawing (GD) functions in PHP here.

Some of the common ones are:

  1. bool ImageLine ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )
  2. bool ImageEllipse resource $image int $cx int $cy int $width int $height int $color 
  3. bool ImageArc resource $image int $cx int $cy int $width int $height int $start int $end int $color )

I think we should also discuss a little about one function, to draw text on out image, it’s called the ImageString() function having the following form:

bool ImageString resource $image int $font int $x int $y string $string int $color )


$img ImageCreateTrueColor(100, 100);
$red ImageColorAllocate($img25500);
ImageString($img7, 10, 10'Text'$red);
ImageString($img, 510, 30'Smaller Text'$red);

The above lines will draw two string of text and the first one will have a bigger font size. Higher number fonts (for $font) are bigger.

All done,now we have a completed image that just needs to be sent to the browser. For this we first need to tell the browser what type of content we’re going to send and the data (image) itself. The following two lines will do this:

header('Content-Type: image/png');

Similarly you can output image in other formats also, just replace ImageJPEG with ImageGIF or ImagePNG etc. and the content-type header to image/gif or image/png accordingly.

After having output the image there is one more thing we should take care of-freeing up the resources. You know images can take up significant amount of resources which may affect the server and other scripts running on it, so always use the following function:

bool ImageDestroy resource $image )

The following example code illustrates all, what we have learnt:

 * DESCRIPTION: Exmple program to illustrate            *
 *              image generation using PHP.             *
 * AUTHOR:      Arvind Gupta                            *
 *              (          *
 * DATE:        21-Mar-09                               *
 * WEBSITE:                                             *
 *   *
// Set width and height
$width 200;

// Create canvas
$img ImageCreateTrueColor($width$height);

// Allocate colors
$gray ImageColorAllocate($img200200200);
$red ImageColorAllocate($img25500);
$green ImageColorAllocate($img02550);
$blue ImageColorAllocate($img00255);

// Fill background color

// Draw
ImageRectangle($img55, ($width 5), ($height 5), $red);
ImageLine($img5, ($width 5), ($height 5), $red);
ImageEllipse($img, ($width 2), ($height 2), ($width 10), ($height 10), $green);
ImageArc($img, ($width 2), ($height 2), ($width 40), ($height 40), 180 360$blue);
ImageArc($img, ($width 2), ($height 2), ($width 60), ($height 60), 180$green);
ImageString($img7, ($width 2) - 50, ($height 2) - 10'Image Created'$red);
ImageString($img7, ($width 2) - 30, ($height 2) + 10'Using PHP'$green);

// Output
header('Content-Type: image/png');

// Free-Up

NOTE: You need to enable the “gd2” extension from “php.ini” for all this to work. See Installing/Configuring Image Support in PHP for more information.

Okay, end of this post. Keep checking back for more.

Popular posts from this blog

Fix For Toshiba Satellite "RTC Battery is Low" Error (with Pictures)

RTC Battery is Low Error on a Toshiba Satellite laptop "RTC Battery is Low..." An error message flashing while you try to boot your laptop is enough to panic many people. But worry not! "RTC Battery" stands for Real-Time Clock battery which almost all laptops and PCs have on their motherboard to power the clock and sometimes to also keep the CMOS settings from getting erased while the system is switched off.  It is not uncommon for these batteries to last for years before requiring a replacement as the clock consumes very less power. And contrary to what some people tell you - they are not rechargeable or getting charged while your computer or laptop is running. In this article, we'll learn everything about RTC batteries and how to fix the error on your Toshiba Satellite laptop. What is an RTC Battery? RTC or CMOS batteries are small coin-shaped lithium batteries with a 3-volts output. Most laptops use

The Best Way(s) to Comment out PHP/HTML Code

PHP supports various styles of comments. Please check the following example: <?php // Single line comment code (); # Single line Comment code2 (); /* Multi Line comment code(); The code inside doesn't run */ // /* This doesn NOT start a multi-line comment block /* Multi line comment block The following line still ends the multi-line comment block //*/ The " # " comment style, though, is rarely used. Do note, in the example, that anything (even a multi-block comment /* ) after a " // " or " # " is a comment, and /* */ around any single-line comment overrides it. This information will come in handy when we learn about some neat tricks next. Comment out PHP Code Blocks Check the following code <?php //* Toggle line if ( 1 ) {      // } else {      // } //*/ //* Toggle line if ( 2 ) {      // } else {      // } //*/ Now see how easy it is to toggle a part of PHP code by just removing or adding a single " / " from th

Pong Game in HTML & JavaScript (Updated)

HTML Pong Game Gameplay Pong is one of the first games that many people from the 80s or 90s had played as children. Lots of people know it as a simple arcade game but what they probably do not know is that this simple game helped establish the video game industry! In this post, we'll be making our version of a very simple but fully working Pong game in HTML, CSS and JavaScript. Basic Game Structure Games, however simple or complex they may be, follow the basic Game Loop design as shown in the chart below. Event-oriented game engines usually encapsulate the design and provide you with an event mechanism for handling various parts like the input, update, and rendering but internally the basic design is being followed. Pong Game Loop For our Game Loop, we'll be using JavaScript setInterval so that the game code remains asynchronous and separate. As you may have guessed a while (or any other loop) will freeze the page. For our input, we'll be using onmousemove event to update t