Adding Validation to an Image Generator Class with PHP 5

Among the plethora of applications that can be developed with PHP 5, building dynamic image streams is one of the easiest to tackle. It requires only an intermediate background in the functions that come packaged with the powerful GD extension. This series of articles will teach you how to use this graphic library to build a highly expansible image generator class that can be used to create noisy images (also known as captchas).

Introduction

Welcome to the second installment of the series that began with "Building a Image Generator Class with PHP 5." In accordance with the series title, these tutorials will guide you through the development of a highly pluggable PHP 5-driven class, which can be useful for embedding dynamically several input strings into a variety of popular graphic formats, including JPG, GIF and PNG.

If you already read the preceding article of the series, I assume that the logic implemented by the image generator class that I developed in that tutorial is now familiar to you. However, to clarify the way this class did its business, let me quickly refresh some key concepts regarding its programmatic functionality.

As you"ll probably recall, the class in question was provided with the ability to create dynamic image streams which contained an embedded text string that was logically passed as an input argument to the class constructor. Also, even though the structure of this class was rather primitive, it was flexible enough to allow us to perform some useful tasks, like displaying on the browser different text strings in a specific graphic format.

Of course, if you analyze the functionality of this image generator class, you might find it rather limited. Nonetheless, it"s possible to couple the class in its current version to other web applications, including banner and noisy images systems.

But, actually I’m getting ahead of myself. In this second part of the series I’ll show you how to introduce some important modifications to the initial skeleton of the image generator class, to make it slightly more modular and independent, while maintaining its functionality nearly the same as before. Sounds pretty interesting, right?

So, having already introduced the subject of this second installment of the series, it’s time to learn how to modify the original signature of this PHP 5-driven image generator class to improve its overall structure. Are you ready to begin? Let’s get started!

{mospagebreak title=Recalling the initial definition of the image generator class}

Before I introduce the modifications that I mentioned in the beginning of this article, I’d like to list the complete source code for the image generator class as it was initially defined in the first tutorial of the series. I believe this will give you a much better idea of how these improvements will affect the functionality of the class in question.

Thus, having clarified this important point, here’s the full signature of the "ImageGenerator" class as it was built in the previous installment of this series:

// 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);

 }

}

Okay, now that you remember how the signature of the above image generator class originally looked, please examine the following pair of code samples. They demonstrate a simple utilization of this class. Here they are:

// 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();

}

Having demonstrated how to use the "ImageGenerator" class to display on the browser some primitive input strings in PNG format, it’s time to analyze in detail its pitfalls. First, as you can see, the structure of the class is pretty flexible, but definitely doesn’t allow you to perform a decent validation on its incoming parameters.

Naturally, this crucial issue should be fixed quickly to make the class slightly more efficient. Thus, in the course of the next section, I’ll be introducing some important modifications to the constructor of the class, so it can perform an adequate validation on all of its input arguments.

To see how these improvements will be added to the image generator class, please click on the link that appears below and keep reading.

{mospagebreak title=Validating incoming parameters}

As I stated in the prior section, the original signature of the "ImageGenerator" class lacked an important feature, the ability to perform an adequate validation on all of its incoming parameters. Since this capacity should be properly incorporated into the class, I will modify the initial implementation of the constructor to provide it with the capacity to check the validity of the different parameters taken by the class.

Given that, here’s how the "ImageGenerator" class now looks after modifying the definition of its constructor method:

// define ‘ImageGenerator’ class (improved version – performs a
basic validation on its incoming parameters)

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′){

  if(strlen($inputString>255)){

   throw new Exception(‘Invalid length for input string.’);

}

  if(!is_int($width)&&$width>800){

   throw new Exception(‘Invalid width for image stream.’);

}

  if(!is_int($width)&&$height>600){

   throw new Exception(‘Invalid height for image stream.’);

}

if(!preg_match("/^d{1,3},d{1,3},d{1,3}$/",$bgColor)||!preg_match
("/^d{1,3},d{1,3},d{1,3}$/",$textColor)){

throw new Exception(‘Invalid format for background or text color.’);

}

  $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 of this method goes here

}

 

// display image stream on the browser

  public function displayImage(){

// implementation of this method goes here

 }

}

As you can see, the constructor of the above "ImageGenerator" class incorporates a few additional lines of code for validating individually each of its incoming parameters, before assigning them as class properties. Of course, this checking process could be improved, particularly if you need to perform a strict validation on the respective input arguments, but I think that the current checking process is more than enough.

So far, so good. At this stage I already showed you how to improve the implementation of the constructor that belongs to the "ImageGenerator" class, with the purpose of making it slightly more efficient and robust. So, what’s the next step?

Well, since the signature of the previous image generator class now looks more compact and solid, I believe that it’s time to reassemble its different parts, and develop a concrete example where its functionality can be tested, at least at a very basic level.

Considering this scenario, in the upcoming section of this tutorial I’ll be showing you the complete (and improved) source code of this image generator class so you can see how it can be used to display several text strings in PNG format.

As I said before, this will be done in the next few lines, so click on the link shown below and keep reading.

{mospagebreak title=The improved signature of the ImageGenerator class}

In consonance with the concepts that I deployed in the section that you just read, the only thing that remains to be covered here is demonstrating a basic implementation of the image generator class, including the improvements that I introduced earlier to the corresponding constructor.

Below I listed the entire definition of the class in question, along with a basic practical example, which simply shows how to output a sample text string on the browser in PNG format.

The corresponding code sample is as follows:

// define ‘ImageGenerator’ class (improved version)

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′){

  if(strlen($inputString>255)){

   throw new Exception(‘Invalid length for input string.’);

}

  if(!is_int($width)&&$width>800){

   throw new Exception(‘Invalid width for image stream.’);

}

  if(!is_int($width)&&$height>600){

   throw new Exception(‘Invalid height for image stream.’);

}

if(!preg_match("/^d{1,3},d{1,3},d{1,3}$/",$bgColor)||!preg_match
("/^d{1,3},d{1,3},d{1,3}$/",$textColor)){

throw new Exception(‘Invalid format for background or text color.’);

}

  $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]);

  $font=imageloadfont($this->font);

if(!imagestring($this->img,$this->font,$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 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();

}

After studying the improved definition for the above image generator class, you’ll certainly agree with me that outputting different strings in a predetermined graphic format is actually a no-brainer process that can be performed with minor problems.

As usual, you’re completely free to modify all the code samples shown here and add your own improvements. It’s really fun, trust me!

Final thoughts

As demonstrated in this second article of the series, the image generator class is quite useful for displaying text strings in a predefined graphic format. However, maybe you’re wondering at this very moment: what’s the point in doing this? Well, as I explained before, the class on its own may seen rather useless, but when combined with other PHP applications, it can be utilized to embed plain texts into different image streams to generate dynamic banners, or the so-called noisy images.

However, the creation of noisy images with the previous image generator class will be covered in detail in the last part of the series, so you don’t have any excuses to miss it!

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

chat sex hikayeleri Ensest hikaye