Drawing More Complex Shapes with the GD Library in PHP

The GD library that comes bundled with PHP 4 and PHP 5 provides web developers with a robust set of intuitive functions for generating and handling dynamic graphics with minor hassles. If you’re interested in mastering the numerous features integrated with this PHP extension, this series of instructive tutorials will make the whole learning experience a truly painless process.

Introduction

Welcome to the fourth part of the series that began with "A Close Look at the GD Library in PHP." This series introduces the most useful functions that come packaged with this powerful graphic PHP library. It also covers the utilization of the library from a practical point of view, since it includes numerous, easy-to-follow code samples.

So far, so good. Having introduced (at least basically) the topics covered by this series, and provided that you have already read its preceding articles, I’d like to spend a few moments summarizing the concepts that you hopefully learned so far concerning the use of the functions included with the GD extension.

In the previous article of the series, I showed you how to take advantage of the remarkable functionality of this PHP extension to display different types of basic arcs on the browser. I also covered outputting some basic characters. The GD functions that perform all of these drawing tasks are extremely simple to use, since most of them take a few intuitive input parameters to display the shapes.

It is this simplicity that makes the library very appealing for many PHP developers. Performing common tasks such as creating several image streams on the fly, or appending different text strings to an existing background picture, are all processes that can be achieved by utilizing a few straightforward functions.

All right, now that I have refreshed your memory of how to use the GD library to display distinct kinds of arcs on the browser, I believe that it’s time to continue exploring many other handy functions that come integrated with this extension. Speaking more specifically, in this fourth tutorial of the series, I’ll show you how to draw some additional shapes, such as filled arcs, and ellipses, along with creating dynamically different types of polygons and retrieving basic information about a given image stream.

With the preliminaries out of the way, let’s learn together how to use the GD library to easily perform all of these tasks. It’s going to be an educational experience, trust me!

{mospagebreak title=Displaying filled images and arcs}

As I stated in the beginning of this series, the GD extension is useful for creating dynamic image streams from scratch, and offers a remarkable capacity for preprocessing existing graphics. Now we are going to see how well it fills up different types of basic shapes before displaying them on the browser.

This is the purpose of the brand new "imagefill()" and "imagefilledarc()" functions. As their names suggest, they perform a filling operation on a given image stream. The function called "imagefill()" performs a flood fill on a specified image; its use is shown in the code sample below: 

// example of ‘imagefill()’ function

try{
   if(!$img=imagecreatetruecolor(300,200)){
     throw new Exception(‘Error creating image’);
   }
   // allocate blue color
   $blue=imagecolorallocate($img,0,0,255);
   imagefill($img,0,0,$blue);
   header("Content-type: image/gif");
   imagegif($img);

}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

As you can see, the "imagefill()" function is really handy for flood filling a specified image stream with a predefined foreground color. It starts this operation at the X, Y coordinates, which are naturally specified as part of the corresponding input parameters.

So far, so good, right? Now that you hopefully learned how the "imagefill()" GD function works, let me show you another example. In this case, the "imagefilledarc()" is used, not surprisingly, to fill in a basic arc with a specific foreground color.

That being explained, here’s the corresponding code sample that shows a simple implementation for this function:

// example of ‘imagefilledarc()’ function try{
   if(!$img=imagecreatetruecolor(300,200)){
     throw new Exception(‘Error creating image’);
   }
   // allocate blue color
   $blue=imagecolorallocate($img,0,0,255);
   // draw filled arc
   imagefilledarc($img,50,50,100,50,0,90,$blue,IMG_ARC_PIE);
   header("Content-type: image/gif");
   imagegif($img);

}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

In this case, the "imagefilledarc()" function that comes bundled with the GD library is used to display a filled arc with a predetermined foreground color on the browser. Also, the referenced function takes the starting and ending coordinates of the arc as its input parameters, along with the image stream used to display the filled shape.

Given that, the image created by the previous hands-on example is similar to the one shown below:

Certainly, after you analyze in detail the previous practical example, you’ll agree with me that drawing and flood filling basic shapes by using the specific functions provided by the GD extension is truly a no-brainer process that can be performed with minor difficulties. Thus, having covered these two handy functions of this library, it’s time to explore others that are also part of the library.

In the following section I’ll teach you how to use a few additional functions that come packaged with the GD extension to display some other filled shapes on the browser, like basic polygons.

Want to see how this will be achieved? Click on the link that appears below and keep reading.

{mospagebreak title=Drawing filled polygons with the GD library}

As I explained in the previous section, the GD library comes bundled with functions that display different types of polygons on the browser. I’m going to show you a couple of new functions for drawing filled rectangles, along with polygons that have more than four sides.

That being said, please take a look at the following code sample. It demonstrates how to use the "imagefilledrectangle" GD function. This function is tasked with displaying different flood filled rectangles on the browser. Here is how the example in question looks:

// example of ‘imagefilledrectangle()’ function – draws a white
rectangle

try{
   if(!$image=imagecreatetruecolor(300,200)){
     throw new Exception(‘Error creating image’);
   }
   // allocate some basic colors
   if(!$whiteColor=imagecolorallocate($img,255,255,255)){
     throw new Exception(‘Error allocating color’);
   }
   // draw a white rectangle
   imagefilledrectangle($image,10,10,100,100,$whiteColor);
   // display image to the browser
   header("Content-type: image/gif");
   imagegif($image);
   // free memory
   imagedestroy($image);

}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

As shown above, the handy "imagefilledectangle()" function can be useful for displaying quickly a rectangle which has been previously filled with a given foreground color. In this case, the example displays a basic white rectangle positioned at the X,Y coordinates specified by the respective input parameters. This generates an image similar to the one shown below:

All right, now that you hopefully learned how the previous "imagefilledrectangle()" function works, please pay close attention to the following example. It shows a simple implementation for another handy drawing function, called "imagefilledpolygon()". As you might have guessed, this one draws a predefined polygon, filled with a given foreground color. The way that this operation is carried out is demonstrated by the script below:

// example of ‘imagefilledpolygon()’ function

try{
   if(!$img=imagecreatetruecolor(300,200)){
     throw new Exception(‘Error creating image’);
   }
   // define polygon coordinates
   $coord= array(10,50,50,100,100,30,30,10);
   // allocate blue color
   $blue=imagecolorallocate($img,0,0,255);
   // draw filled polygon
   imagefilledpolygon($img,$coord,4,$blue);
   header("Content-type: image/gif");
   imagegif($img);

}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

Certainly, the "imagefilledpolygon()" function is very convenient for displaying on the browser different types of polygons which have been previously filled with a specified foreground color. The final image created by the previous script looks similar to this one: 

So far, so good. At this point, I have shown you a considerable number of functions provided by the GD extension that can be used to perform all sorts of flood filling tasks on distinct shapes. This feature makes this library quite helpful for generating more complex graphics from primitive forms.

Thus, considering that the way all of these functions work is simple to grasp, I’ll dedicate the last section of this tutorial to covering a few more handy functions packaged with this graphical library. These functions can be utilized for retrieving specific information about a given image stream, quickly and easily.

As you’ll see in a moment, these functions are really useful, so jump ahead and read the next few lines. I’ll be there, waiting for you.

{mospagebreak title=Retrieving information about a given image stream}

In consonance with the concepts that I discussed in the section you just read, this last section will be focused upon covering the functions integrated with the GD package that retrieve the physical dimensions of a given image stream.

To perform these tasks, the library offers the handy "imagex()" and "imagey()" functions, which can be used to retrieve the width and height of a specified image respectively.

A pair of simple implementations for these functions is shown below, so study the corresponding code samples:

// example of ‘imagesx()’ function

try{
   if(!$image=imagecreatetruecolor(300,200)){
     throw new Exception(‘Error creating image’);
   }
   // display image width
   echo ‘The image is ‘.imagesx($image).’pixels width';
   // displays: The image is 300pixels width
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

// example of ‘imagesy()’ function try{
   if(!$image=imagecreatetruecolor(300,200)){
     throw new Exception(‘Error creating image’);
   }
   // display image height
   echo ‘The image is ‘.imagesy($image).’pixels height';
   // displays: The image is 200pixels height
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

Admittedly, getting the width and height values of a given image stream is actually a straightforward procedure, considering the simplicity of the functions. As you saw, they only take a reference of the image stream used to calculate its respective dimensions. Quite easy, right?

Finally, as I said earlier, the GD library also offers another powerful function that fetches relevant information on a concrete image stream. This function is called "getimagesize()." It not only retrieves the respective width and height of the stream, but returns its MIME type as well in an array notation.

Below I coded a demonstrative example that shows how to use this function: 

// example of ‘getimagesize()’ function

   if(!$imageData=getimagesize(‘clouds.gif’)){
     throw new Exception(‘Error getting image data’);
   }
   // display image data
   echo ‘Image data is as following<br />';
   echo ‘Image width: ‘.$imageData[0].’px <br />';// Image
width :300px 
   echo ‘Image height: ‘.$imageData[1].’px <br />';// Image
height :200px
   echo ‘MIME type: ‘.$imageData['mime'].'<br />';// MIME type:
image/gif

}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

See how easy it is to retrieve relevant information about a given image stream using the previous "getimagesize()" function? I’m sure you do! Of course, it’s worthwhile to mention here that all of the examples included in this tutorial are just that: a friendly introduction to using the most important functions bundled with the GD extension. For full information about this package, the best place to go is the PHP official site.

Final thoughts

In this fourth part of the series, I walked you through using the GD functions that draw basic filled shapes, ranging from simple rectangles to more complex polygons. I also showed you a few additional functions for retrieving the dimensions of a specified image stream.

In the last part of the series, I’ll teach you how to take advantage of the capacity offered by the GD package to apply different types of filters to an existing graphic.

Now that you’ve been warned, I think you won’t want to miss it!  

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

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort