A Close Look at the GD Library in PHP

The GD library comes bundled with both PHP 4 and PHP 5. While it is a popular library that has been around for a while, many web developers do not take full advantage of its capabilities. In this five-part series, we will take a close look at what the GB library can do for you, especially in the area of dynamically-generated graphics.

Introduction

PHP is a general-purpose, server-side scripting language which can be used to develop a plethora of applications, ranging from simple web form processing mechanisms, to complex, full-featured database-driven web sites. Its remarkable versatility, which makes it suitable for tackling quickly the development of a huge variety of projects, along with its extremely easy learning curve, have turned PHP into one of the languages web developers prefer to use.

And frankly speaking, this is more evident than ever when it comes to exploring PHP’s powerful capacities for generating images on the fly via its popular GD library. This PHP extension has been available for a long time to PHP developers, but quite frequently its functionality has been under appreciated, since the number of web applications that require the implementation of dynamically-generated graphics is rather limited.

However, it’s fair to mention that the GD library that comes bundled with PHP 4, and PHP 5 as well, can be extremely useful in situations where it’s necessary to display a certain number of graphics that need to incorporate one or more dynamic components. This category includes statistic systems, image galleries, noisy images, etc., to name the most popular applications that truly can take advantage of the numerous benefits offered by the GD extension.

Therefore, to summarize, it’s very clear that generating dynamic graphics with PHP 4/PHP 5 can be quite useful for a number of specific PHP applications. Bearing this in mind, over the course of this series of approachable tutorials, I’ll be taking a close look at the most useful functions of this graphical extension, complementing the theoretical descriptions with illustrative hands-on examples.

In this manner, by the end of this series you’ll be decently equipped to start incorporating the neat functionality provided by the GD library into your own PHP applications, assuming that your web projects eventually require the implementation of dynamically-generated graphics.

Now that you know the topics that will be covered in this series of articles, it’s time to start learning the numerous functions that come bundled with the GD extension. Let’s begin this educational journey now!

{mospagebreak title=Creating images from scratch with the GD library}

We will start exploring the numerous functions that come bundled with the GD extension by showing how to create a dynamic image from scratch. In this case, this basic task can be performed by using three core GD functions, called "imagecreate()", "imagecolorallocate()" and "imagestring()" respectively.

Concerning the usage of the aforementioned functions, below I coded a simple example, which shows how to utilize these functions:

// example of ‘imagecreate()’, ‘imagecolorallocate()’,
‘imagestring()’ functions
try{
   if(!$image=imagecreate(300,200)){
     throw new Exception(‘Error creating blank image’);
   }
   // create background color for image
   $backColor=imagecolorallocate($image,0,0,255);
   // create text color
   if(!$textColor=imagecolorallocate($image,255,255,255)){
     throw new Exception(‘Error creating text color’);
   }
   // include text string into image stream
   if(!$text=imagestring($image,5,10,90,’This is a sample text
string.’,$textColor)){
     throw new Exception(‘Error creating image text’);
   }
   header("Content-type:image/png");
   // display image
   imagepng($image);
   // free up memory
   imagedestroy($image);
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

Basically, all the previous examples does is create a 300px X 200px image stream via the "imagecreate()" function, then allocate a white color into the stream by the means of "imagecolorallocate()", and finally include a sample string by using the "imagestring()" function. Two additional functions are used in the proper sequence, that is "imagepng()" and imagedestroy()" to output the image in PNG format to the browser, and free up the memory occupied by the respective image.

The PNG image generated by the previous example is shown below:

As you saw, the above example not only demonstrates how easy it is to create an image from scratch with the GD extension, but how intuitive its main functions are, right?

Also, in a similar fashion, the example can be quickly rewritten, this time using a simple procedural function. This approach is illustrated by the code sample below:

try{
  
// define procedural function
  
function displayTextOnImage($text=’This is a sample text
string’){
     if(!$text){
       throw new Exception(‘Invalid text string’); 
     }
     if(!$image=imagecreate(300,200)){
       throw new Exception(‘Error creating blank image’);
     }
     // create background color for image
     $backColor=imagecolorallocate($image,0,0,255);
     // create text color
     if(!$textColor=imagecolorallocate($image,255,255,255)){
       throw new Exception(‘Error creating text color’);
     }
     // include text string into image stream
     if(!imagestring($image,5,10,90,$text,$textColor)){
       throw new Exception(‘Error creating image text’);
     }
     header("Content-type:image/png");
     // display image
     imagepng($image);
     // free up memory
     imagedestroy($image);
   }
   // display image on the browser
   displayTextOnImage(‘This text was created with GD.’);
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

Of course, as you might have guessed, the custom "displayTextOnImage()" function that I defined previously displays a new PNG image on the browser, similar to the one shown below:

All right, now that you hopefully learned how to create an image from scratch by using a few intuitive functions bundled with the GD library, it’s a good time to move forward and continue analyzing other useful functions. Thus, in the following section I’ll show you how to utilize an alternative GD function to generate basic image streams.

To learn how this brand new function will be used, please click on the link below and keep reading.

{mospagebreak title=An alternative way to create image streams from scratch}

In accordance with the concepts that I expressed in the earlier section, the GD extension offers yet another function that is very useful for creating image streams from scratch. I’m talking about the "imagecreatetruecolor()" function, which can be used in the following way:

// example of ‘imagecreatetruecolor()’, ‘imagecolorallocate()’,
‘imagestring()’ functions
try{
   if(!$image=imagecreatetruecolor(300,200)){
     throw new Exception(‘Error creating blank image’);
   }
   // create text color for image
   if(!$textColor=imagecolorallocate($image,255,255,255)){
     throw new Exception(‘Error creating text color’);
   }
   // include text string into image stream
   if(!$text=imagestring($image,5,10,90,’This is a sample text
string.’,$textColor)){
     throw new Exception(‘Error creating image text’);
   }
   header("Content-type:image/png");
   // display image
   imagepng($image);
   // free up memory
   imagedestroy($image);
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

As illustrated previously, the "imagecreatetruecolor()" functions behaves very similar to its cousin "imagecreate()" covered in the prior section. However, in this case, the function in question creates a true color image stream, which can be slightly more useful if you want to generate obviously true-color graphics. Other than that, the function takes up the same input parameters, and returns an image identifier if the stream has been successfully created.

That being explained, the image outputted to the browser by the previous example is depicted below:

In addition, the source code of the previous example could be easily wrapped into a custom function, in the following manner:

// example of ‘imagecreatetruecolor()’, ‘imagecolorallocate()’,
‘imagestring()’ functions
try{
  
function displayTextOnImage($text=’This is a sample text
string’){
     if(!$text){
       throw new Exception(‘Invalid text string’); 
     }
     if(!$image=imagecreatetruecolor(300,200)){
       throw new Exception(‘Error creating blank image’);
     }
     // create text color
     if(!$textColor=imagecolorallocate($image,255,255,255)){
       throw new Exception(‘Error creating text color’);
     }
     // include text string into image stream
     if(!imagestring($image,5,10,90,$text,$textColor)){
       throw new Exception(‘Error creating image text’);
     }
     header("Content-type:image/png");
     // display image
     imagepng($image);
     // free up memory
     imagedestroy($image); 
   }
   displayTextOnImage(‘This text was created with GD.’);
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

All right, at this point, after studying all of the code samples, you’ll have to agree with me that building dynamic graphics from scratch by using the GD extension is actually a very intuitive process that can be performed with minor hassles.

Therefore, provided that you have already grasped the programming logic required to create basic images with this powerful graphical extension, in the following section I’ll show you some additional hands-on examples aimed at demonstrating how to build dynamic graphics from an existing GIF image, using practically the same GD functions that you learned previously. Sounds really interesting, right?

To learn more on how to create image streams from an existing GIF image using the functionality provided by the GD extension, jump ahead and read the next few lines. I’ll be there, waiting for you.

{mospagebreak title=Generating dynamic streams from existing GIF images with the GD library}

As you possibly recall from the previous section, I said that the GD extension allows you to not only create image streams from scratch, but also generate different graphics from existing images. This feature is particularly useful in those cases where you want to use a previously-built picture and create a different image from it.

To achieve this process effortlessly, the GD library comes equipped with a decent set of functions aimed specifically at generating image streams from an existing graphic. In this case, I’ll show you how to use the "imagecreatefromgif()" function, but in upcoming articles of this series, I’ll teach you how to utilize some others too.

Thus, assuming that the following sample GIF image has been previously created by using a graphic editing software, a scanner or a digital camera:

Then the "imagecreatefromgif()" function might be used as follows:

// example of ‘imagecreatefromgif()’ function
try{
   if(!$image=imagecreatefromgif(‘clouds.gif’)){
     throw new Exception(‘Error loading image’);
   }
   // create text color for gif image
   if(!$textColor=imagecolorallocate($image,0,0,0)){
     throw new Exception(‘Error creating text color’);
   }
   // include text string into gif image
   if(!$text=imagestring($image,5,10,90,’This is a sample text
string.’,$textColor)){
     throw new Exception(‘Error creating image text’);
   }
   header("Content-type:image/gif");
   // display image
   imagegif($image);
   // free up memory
   imagedestroy($image);
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

As you can see, the above example uses an existing GIF image, and displays on top of it a sample text string by using the same functions that you learned previously. And finally, the example outputs to the browser the following GIF image:

See how easy it is to create a brand new image from an existing one using the GD library? Of course you see that! Besides, the previous "imagecreatefromgif()" function could be quickly wrapped into a custom function, as demonstrated by the example below:

// example of custom function using ‘imagecreatefromgif()’
try{
   // define ‘displayGifImage()’ function
   function displayGifImage($image,$text){
     if(!file_exists($image)){
       throw new Exception(‘Invalid image file’);
     }
     if(!$text){
       throw new Exception(‘Invalid text for image’);
     }
     if(!$image=imagecreatefromgif($image)){
       throw new Exception(‘Error loading image’);
     }
     // create text color for gif image
     if(!$textColor=imagecolorallocate($image,0,0,0)){
       throw new Exception(‘Error creating text color’);
     }
     // include text string into gif image
     if(!imagestring($image,5,10,90,$text,$textColor)){
       throw new Exception(‘Error creating image text’);
     }
     header("Content-type:image/gif");
     // display image
     imagegif($image);
     // free up memory
     imagedestroy($image); 
   }
   displayGifImage(‘clouds.gif’,’This is a sample string.’);
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

As you might guess, the previous custom "displayGifImage()" is only a crude wrapper for the already familiar "imagecreatefromgif()" function that comes bundled with the GD library. However, this example should give you a clear idea of how to develop more complex functions or classes that use this function to generate new image streams from an existing graphic.

Lastly, as usual with many of my articles on PHP development, feel free to tweak all of the source code corresponding to the examples shown in this tutorial. In this manner you can acquire a more complete background in the GD extension.

Final thoughts

In this first tutorial of the series, I introduced some basic functions integrated with the GD extension, to demonstrate how to perform some useful things, such as creating image streams from scratch, displaying text strings and generating new GIF graphics utilizing existing ones.

However, this is merely the beginning of this journey, since the GD library comes equipped with many more useful functions. Some of them will be covered in the next part of the series. You won’t want to miss it!

[gp-comments width="770" linklove="off" ]

chat