Building an Image Generator Class with PHP 5

In this article, you will learn how to build an image generator class with PHP 5, using the functions bundled with the GD library. Such a class has a wide variety of uses, but for the purposes of this three-part series, we will focus on creating a function for displaying noisy images (also known as captchas) on the browser.

Introduction

Undeniably, PHP is widely recognized by many web programmers as a general server-side scripting language with a remarkable capacity for tackling the development of a huge variety of applications. These applications can range from basic form validation classes and efficient database abstraction layers to more complex projects, such as fully-featured discussion forums, powerful web-based MySQL front-ends and popular content management systems.

The release of PHP 5 has provided seasoned PHP developers with a robust set of functions and object-based features that make this version of the scripting language one of the most used for building robust web applications with minor hassles. This versatility is particularly in evidence when it comes to generating and manipulating dynamic image streams via the popular GD extension. This library comes packaged with a neat arsenal of graphic processing functions for quickly and easily developing image-centric applications.

However, it isn’t my intention to provide you a with a detailed guide on how to put the GD extension to work for you, since I already wrote an extensive series of articles, which were published here, on the prestigious Developer Shed Network.

Instead, I’d like to take a different course of action, slightly more pragmatic, and show you how to utilize some of the functions bundled with the GD library to build a highly expansible image generator class. Thanks to its fairly skeletal structure, this class will be easy to customize to suit the requirements of different PHP applications.

In simple terms, over the course of this brand new PHP series, which will be comprised of three friendly tutorials, I’ll walk you through the development of an easy-to-follow PHP class that will have the ability to build dynamic text strings, which will be outputted straight to the browser in the form of image streams.

Of course, if you reread the previous sentence, then you’ll realize the huge range of PHP applications that might take advantage of the basic functionality provided by the class that I plan to create here. In this case, however, I’ll focus the whole development process on using the class in question to build an application aimed at displaying noisy images (also widely known as captchas).

The structure of this image generating class will be extremely pluggable, which implies that you can use it for other purposes, but hopefully the whole learning experience will serve as an introduction to using some functions included with the GD extension in the context of the object-oriented paradigm.

All right, providing that the development of an image generator class with PHP 5 may be an interesting topic to you, let’s not waste more time in preliminaries and start building the core structure of this PHP 5-based class. It’s going to be an instructive journey, trust me!

{mospagebreak title=Defining the basic structure of a image generator class in PHP 5}

As I explained in the beginning of this article, the initial structure of this image generator class will be rather simplistic. It will be composed of only two basic methods (except for the corresponding constructor), called "buildImageStream()" and "displayImage()" respectively.

Obviously, as these names suggest, the first one will be tasked with building dynamically an image stream, while the second one will output it on the browser using a specific graphic format.

Having said that, here’s the basic signature of this image generator class. Have a look at it, please:

// define ‘ImageGenerator’ class

  class ImageGenerator{

   private $width;

   private $height;

   private $bgColor;

   private $textColor;

   private $inputString;

   private $img;

// initialize input arguments

public function __construct($inputString=’Default Input String’,$width=400,$height=300,$bgColor=’0,0,0′,
$textColor=’255,255,255′){

  $this->inputString=$inputString;

   $this->width=$width;

   $this->height=$height;

   $this->bgColor=explode(‘,’,$bgColor);

   $this->textColor=explode(‘,’,$textColor);

   $this->buildImageStream();

}

// create image stream

  private function buildImageStream(){

// implementation for this private method goes here

// display image stream on the browser

  public function displayImage(){

// implementation for this public method goes here

 }

}

As you can see, the definition of the above "ImageGenerator" class is very easy to follow, even though it’s still incomplete. First, you may notice that the constructor takes up a few simple incoming parameters. These include the corresponding input string that will be embedded in the graphic output, and then the dimensions of the image stream being generated, and finally the foreground and background colors.

Additionally, it’s clear to see that the constructor also calls the private "buildImageStream()" method from inside its context. This will come in handy for generating the respective dynamic image stream on the fly, based upon the pertinent input arguments. However, for the sake of clarity, the implementation of this method and the "displayImage()" method will be covered in detail in the section to come.

Thus, if you’re interested in learning how these brand new methods that belong to the image generator class will be defined, please jump ahead and read the next few lines. I’ll be there, waiting for you.

{mospagebreak title=Implementing the buildImageStream() and displayImage() methods}

As you might have guessed from the concepts that I deployed in the previous section, completing the definition of this image generator PHP class is a process reduced to implementing the respective "buildImageStream()" and "displayImage()" methods that were declared earlier within the class structure.

Below I have again included the signature of the image generator class in question, including the implementation of the aforementioned class methods.

Having explained that, here’s the complete version of this class, after implementing its corresponding "buildImageStream()" and "displayImage()" methods:

// define ‘ImageGenerator’ class

  class ImageGenerator{

   private $width;

   private $height;

   private $bgColor;

   private $textColor;

   private $inputString;

   private $img;

// initialize input arguments

public function __construct($inputString=’Default Input
String’,$width=400,$height=300,$bgColor=’0,0,0′,
$textColor=’255,255,255′){

  $this->inputString=$inputString;

   $this->width=$width;

   $this->height=$height;

   $this->bgColor=explode(‘,’,$bgColor);

   $this->textColor=explode(‘,’,$textColor);

   $this->buildImageStream();

}

// create image stream

 private function buildImageStream(){

  if(!$this->img=imagecreate($this->width,$this->height)){

   throw new Exception(‘Error creating image stream’);

}

// allocate background color on image stream

imagecolorallocate($this->img,$this->bgColor[0],$this->bgColor
[1],$this->bgColor[2]);

// allocate text color on image stream

$textColor=imagecolorallocate($this->img,$this->textColor
[0],$this->textColor[1],$this->textColor[2]);

if(!imagestring($this->img,5,$this->width/2-strlen($this-
>inputString)*5,$this->height/2-5,$this->inputString,$textColor)){

  throw new Exception(‘Error creating image text’);

 }

}

// display image stream on the browser

 public function displayImage(){

  header("Content-type: image/png");

// display image

  imagepng($this->img);

// free up memory

  imagedestroy($this->img);

 }

}

Certainly, if you take some time to study the signature of the above image generator class, then you’ll agree with me that its business logic is quite simple to grasp. As you can see, the implementations for the methods I mentioned a few lines ago are also simple. In the first case, the "buildImageStream()" method performs some basic tasks, like creating the pertinent image stream, then allocating the appropriate foreground and background colors, and finally embedding into the stream the input text that was initially passed to the constructor. Quite easy to follow, right?

Now, concerning the implementation of the second "displayImage()" method, its functionality is limited to outputting to the browser the respective image stream built previously, in this case using the PNG format via the "imagepng()" function that comes bundled with the GD extension.

Finally the stream is removed from the web server’s memory by calling the "imagedestroy()" function. This procedure should be quite familiar to you if you work with the GD library on a regular basis.

So far, so good, right? At this point, I have completed the development of the previous "ImageGenerator" class, which behaves like a simple wrapper for the most common functions included with the GD extension.

However, you probably want to see how this class can be used in the context of a practical example. Therefore, in the course of the last section of this tutorial I’ll show you some friendly code samples to give you a better idea of how to put this image generator class to work for you.

To see how this brand new hands-on example will be developed, please click on the link below and keep reading.

{mospagebreak title=Testing the ImageGenerator class}

As I stated during the section that you just read, one of the best ways to demonstrate the functionality provided by the previously defined "ImageGenerator" class consists of developing a practical example, where you can see very clearly how it works.

Please take a look at the following code sample, which illustrates how to use the class in question, first for displaying on the browser a default input string, and finally for showing another primitive text.

Given that, the corresponding code sample looks like this, including first the complete definition of the "ImageGenerator" class that you learned previously:

// define ‘ImageGenerator’ class

  class ImageGenerator{

   private $width;

   private $height;

   private $bgColor;

   private $textColor;

   private $inputString;

   private $img;

// initialize input arguments

public function __construct($inputString=’Default Input
String’,$width=400,$height=300,$bgColor=’0,0,0′,
$textColor=’255,255,255′){

  $this->inputString=$inputString;

   $this->width=$width;

   $this->height=$height;

   $this->bgColor=explode(‘,’,$bgColor);

   $this->textColor=explode(‘,’,$textColor);

   $this->buildImageStream();

}

// create image stream

 private function buildImageStream(){

  if(!$this->img=imagecreate($this->width,$this->height)){

   throw new Exception(‘Error creating image stream’);

}

// allocate background color on image stream

imagecolorallocate($this->img,$this->bgColor[0],$this->bgColor
[1],$this->bgColor[2]);

// allocate text color on image stream

$textColor=imagecolorallocate($this->img,$this->textColor
[0],$this->textColor[1],$this->textColor[2]);

if(!imagestring($this->img,5,$this->width/2-strlen($this-
>inputString)*5,$this->height/2-5,$this->inputString,$textColor)){

  throw new Exception(‘Error creating image text’);

 }

}

// display image stream on the browser

  public function displayImage(){

   header("Content-type: image/png");

// display image

  imagepng($this->img);

// free up memory

  imagedestroy($this->img);

 }

}

/* display default input string

  try{

// create new instance of ‘ImageGenerator’ class

  $imgGen=new ImageGenerator();

// display image stream on the browser

  $imgGen->displayImage();

}

  catch(Exception $e){

   echo $e->getMessage();

  exit();

}

// display sample input string

  try{

// create new instance of ‘ImageGenerator’ class

  $imgGen=new ImageGenerator(‘This is a sample string’);

// display image stream on the browser

  $imgGen->displayImage();

}

  catch(Exception $e){

   echo $e->getMessage();

  exit();

}

As shown above, the image generator class in its current incarnation is quite useful for displaying input strings in the format of image streams. The procedure is reduced to creating an instance of the mentioned class with the input text to be outputted, and then calling its respective "displayImage()" method.

In addition, below I included two screen shots, which demonstrate the outputs generated by the previous code samples:

Of course, the functionality of the class analyzed in an isolated context is rather limited. However, it can be quite useful when utilized in conjunction with other applications, for instance, to build noise images. Now, things are getting slightly more interesting, right?

For the moment, I suggest that you test the source code of this image generator class by using several input texts, to see how it works in each particular case.

Final thoughts

That’s all for now. Hopefully, after reading this article, you’ll have a much better idea of how to build a PHP 5-based class that displays an input string in a predefined graphic format.

Nonetheless, the class in its current version has some important limitations, since it doesn’t perform an appropriate validation on all of its input arguments. Therefore, considering this relevant issue, in the next part of the series I’ll fix this issue, thus improving the overall structure of the class.

Now that you know what the next article will be about, you won’t want to miss it!

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

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort