Generating Images with PHP

PHP is often used to generate HTML pages. However, PHP is capable of generating different types of content like music, videos, pdf documents, and images. In this tutorial, you will learn how to generate images on the fly using PHP. We will create a PHP script, that every time it is invoked, it generates an image with a random number. Click here to see the script in action.

To be able to generate images on the fly we need the GD library. So, before we get started generating images, we need to make sure this library is installed and enabled. The code below checks if the library is enabled.

if( function_exists("imagecreatetruecolor") ) {
  print "GD library is enabled!";
}else {
  print "GD library is not enabled!";

This snippet of code checks if imagecreatetruecolor(), which is one the GD’s library function, is defined. If it is defined then GD is enabled, otherwise it is not enabled. Save this snippet of code in a file and run it in your browser. If the script says GD is not enabled then you must read the next section to learn how you can enable it. Otherwise, you may skip the next section.

Enabling the GD library

On Windows, you need to enable the GD extension in the php.ini configuration file. Open the configuration file and search for a line that begins with “;extension=php_gd2.dll” and uncomment it by removing the first “;” (see the screenshot below). Then, save the file and restart your web server, and you are done.

Enabling GD extension on Windows

If you are running Ubuntu, open a shell program and run the command “sudo apt-get install php5-gd”. After that, restart your web server and you are done.

Generating Images

To generate an image using PHP and the GD library, we follow these 3 steps:

  1. Create the image in memory.
  2. Paint the image.
  3. Output the image to the browser.

To create the image, we use the imagecreatetruecolor() function that creates a new black image. It takes as parameters the width and height of the new image. This function returns a resource identifier representing the image. This identifier is later used in all  drawing functions that act upon the image.

After creating the image, we must allocate all the colors we need to draw into the image. For that purpose, we use imagecolorallocate(). This functions takes as parameters the image identifier,  the red, green, and blue values that represent the color we want. It returns a color identifier that represents the color.

Finally, we output the image data to the browser using imagegif(), imagepng() or imagejpeg(). These functions output, respectively, GIF, PNG, and JPEG images. Before outputing the image data, we must tell the browser about the format of our image. To do that, we send a Content-Type header specifying the format of the image. The table below shows some examples of Content-Types (also called Internet Media Types).

Content-Type Description
text/html HTML
image/gif GIF image
image/jpeg JPEG image
image/png PNG image
application/pdf PDF document
audio/mp4 MP4 audio

By default, PHP sets the Content-Type header to text/html. Thus, to output a JPEG image, we must set Content-Type header to image/jpeg. To change headers we use the built-in header() function.

Let’s create a small script that generates a 400×200 JPEG black image with a yellow rectangle inside.

// Create the image.
$im = imagecreatecolor(400,200);

// Allocate yellow color
$white  = imagecolorallocate($im,255,255,255);

// Draw a filled yellow rectangle

// Tell the browser we will output a JPEG image.
header("Content-Type: image/jpeg");

// Output the image data in JPEG format

First of all, we create the image and save the returned identifier in $im. Next, we allocate a yellow color and save the returned identifier in $yellow. After that, we draw a yellow filled rectangle into our image. We use $im to reference our image, and $yellow to reference the yellow color we allocated. Then, we tell the browser we will output a JPEG image, by sending a Content-Type header set to image/jpeg. Finally, we output our image in JPEG format. As you can see, this is pretty simple.

In the table below, I summarize some of the drawing functions you can use to draw into an image. You can find the complete list of the GD library’s functions in this page from the PHP website.

Function Description
imagefilledrectangle($image,$x1,$y1,$x2,$y2,$color) Draws a filled rectangle that starts at point 1 ($x1,$y1) and ends at ($x2,$y2)
imageline($image,$x1,$y1,$x2,$y2,$color) Draws a line from point 1 ($x1,$y1) to point 2 ($x2,$y2)
imagesetpixel($image,$x,$y,$color) Draws a single pixel at the specified coordinate
imagestring($image,$font,$x1,$y1,$string,$color) Draws a string horizontally at the specified coordinate. $font can be a number between 1 and 5. The higher the number the larger is the font.

Now we have enough knowledge to create a script to generate an image with a random number.

// Create the image
$im = imagecreatetruecolor(400,200);

// Allocate a red color.
$red = imagecolorallocate($im,255,0,0);

// Allocate a blue color.
$yellow = imagecolorallocate($im,255,255,0);

// Draw a yellow line from the upper left corner to the lower right corner.

// Draw a yellow line from the lower left corner to the upper right corner.

// Generate a random 4-digit number.
$rnd_num = rand(1111,9999);

// Draw the random number with a red color.

// Tell the browser we will output a PNG image
header("Content-Type: image/png");

// Output the image to the browser in PNG format

First, we create the image. After that, we allocate red and yellow colors. Then, we draw 2 yellow lines. Next, we generate a random 4 digit number. After that, we draw the random number into the image using the largest built-in font and a red color. Finally, we tell the browser we will output a PNG image, and then we send the image data.

Save the above script in a file named image.php. Running this script in the browser will generate a black image with 2 lines underneath a random 4 digit number.

Click here to see the script in action.

We can use the image.php script as the source for img HTML elements tags. Check the code below:

<head><title>Generating Images with PHP: Example</title></head>
<h1>PHP Tips: Generating Images with PHP</h1>
Refresh the page to change the image.
<img src="image.php" alt="" />

Click here to see the html code above in action. The full source code is here.


The GD library provides various functions for image processing. To generate an image, first, we create an in-memory representation of the image using imagecreatetruecolor(). After that, we can draw into the in-memory image using various GD’s function. Before, submitting the image data to the browser, we set an appropriate Content-Type header for the image format. Finally, we submit the image data to the browser.

  1. What happens if I have sent headers already? Because if a page has been loaded and I need to print the image below, it means that I will get an error if I sent another header again.

Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.

Trackbacks and Pingbacks: