Skip to main content

Image Generation Using PHP

Image Generation Using PHP

In one of the previous posts about CAPTCHA Image Generation we made use of PHP’s image generation functions but didn’t discuss about them. So, if you had any problems or just want to know more, read on.

Creating and outputting images from PHP is very simple and easy. And since PHP supports images in a number of different formats you can very easily generate images in various formats such as JPEG, PNG, GIF etc. Generating  images involves the following steps:

  1. Creating a canvas.

  2. Drawing

  3. Outputting the image.

Now, let’s look at each of the steps in detail.

Creating a Canvas

Creating a canvas is very easy, just use the following function:

resource ImageCreateTrueColor int $width int $height )

The capitalization doesn’t matter as with any function in PHP.

If you want your canvas to have some background color (default is black) you can use the following function:

bool ImageFill resource $image int $x int $y int $color )

Where color is to be first allocate using the following function:

int ImageColorAllocate resource $image int $red int $green int $blue )

You can also use an existing image as base canvas for your new image, in that case create your image using the following function:

resource ImageCreateFromJPEG string $filename )

Images in other format can also be used, for PNG →  ImageCreateFromPNG (), GIF → ImageCreateFromGIF ().

Drawing

After having set up the canvas, let’s draw something on it, say, a rectangle. The rectangle drawing function with its argument list is:

bool ImageRectangle resource $image int $x1 int $y1 int $x2 int $y2 int $color )

For allocating color use the ImageColorAllocate() function.

The following will create a square of size 10px X 10px having a blue border:

$img ImageCreateTrueColor(20, 20);
$blue ImageColorAllocate($img00255);
ImageRectangle($img, 0, 0, 10, 10$blue);

You can browse the complete list of drawing (GD) functions in PHP here.

Some of the common ones are:

  1. bool ImageLine ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )
  2. bool ImageEllipse resource $image int $cx int $cy int $width int $height int $color 
  3. bool ImageArc resource $image int $cx int $cy int $width int $height int $start int $end int $color )

I think we should also discuss a little about one function, to draw text on out image, it’s called the ImageString() function having the following form:

bool ImageString resource $image int $font int $x int $y string $string int $color )

Example:

$img ImageCreateTrueColor(100, 100);
$red ImageColorAllocate($img25500);
ImageString($img7, 10, 10'Text'$red);
ImageString($img, 510, 30'Smaller Text'$red);

The above lines will draw two string of text and the first one will have a bigger font size. Higher number fonts (for $font) are bigger.

All done,now we have a completed image that just needs to be sent to the browser. For this we first need to tell the browser what type of content we’re going to send and the data (image) itself. The following two lines will do this:

header('Content-Type: image/png');
ImagePNG($img);

Similarly you can output image in other formats also, just replace ImageJPEG with ImageGIF or ImagePNG etc. and the content-type header to image/gif or image/png accordingly.

After having output the image there is one more thing we should take care of-freeing up the resources. You know images can take up significant amount of resources which may affect the server and other scripts running on it, so always use the following function:

bool ImageDestroy resource $image )

The following example code illustrates all, what we have learnt:

<?
/********************************************************
 * DESCRIPTION: Exmple program to illustrate            *
 *              image generation using PHP.             *
 * AUTHOR:      Arvind Gupta                            *
 *              (http://www.arvindgupta.co.in)          *
 * DATE:        21-Mar-09                               *
 * WEBSITE:                                             *
 * http://learning-computer-programming.blogspot.com/   *
 ********************************************************/
// Set width and height
$width 200;
$height200;

// Create canvas
$img ImageCreateTrueColor($width$height);

// Allocate colors
$gray ImageColorAllocate($img200200200);
$red ImageColorAllocate($img25500);
$green ImageColorAllocate($img02550);
$blue ImageColorAllocate($img00255);

// Fill background color
ImageFill($img00$gray);

// Draw
ImageRectangle($img55, ($width 5), ($height 5), $red);
ImageLine($img5, ($width 5), ($height 5), $red);
ImageEllipse($img, ($width 2), ($height 2), ($width 10), ($height 10), $green);
ImageArc($img, ($width 2), ($height 2), ($width 40), ($height 40), 180 360$blue);
ImageArc($img, ($width 2), ($height 2), ($width 60), ($height 60), 180$green);
ImageString($img7, ($width 2) - 50, ($height 2) - 10'Image Created'$red);
ImageString($img7, ($width 2) - 30, ($height 2) + 10'Using PHP'$green);

// Output
header('Content-Type: image/png');
ImagePNG($img);

// Free-Up
ImageDestroy($img);
?>

NOTE: You need to enable the “gd2” extension from “php.ini” for all this to work. See Installing/Configuring Image Support in PHP for more information.

Okay, end of this post. Keep checking back for more.

Popular posts from this blog

Fix For Toshiba Satellite "RTC Battery is Low" Error (with Pictures)

RTC Battery is Low Error on a Toshiba Satellite laptop "RTC Battery is Low..." An error message flashing while you try to boot your laptop is enough to panic many people. But worry not! "RTC Battery" stands for Real-Time Clock battery which almost all laptops and PCs have on their motherboard to power the clock and sometimes to also keep the CMOS settings from getting erased while the system is switched off.  It is not uncommon for these batteries to last for years before requiring a replacement as the clock consumes very less power. And contrary to what some people tell you - they are not rechargeable or getting charged while your computer or laptop is running. In this article, we'll learn everything about RTC batteries and how to fix the error on your Toshiba Satellite laptop. What is an RTC Battery? RTC or CMOS batteries are small coin-shaped lithium batteries with a 3-volts output. Most laptops use

The Best Way(s) to Comment out PHP/HTML Code

PHP supports various styles of comments. Please check the following example: <?php // Single line comment code (); # Single line Comment code2 (); /* Multi Line comment code(); The code inside doesn't run */ // /* This doesn NOT start a multi-line comment block /* Multi line comment block The following line still ends the multi-line comment block //*/ The " # " comment style, though, is rarely used. Do note, in the example, that anything (even a multi-block comment /* ) after a " // " or " # " is a comment, and /* */ around any single-line comment overrides it. This information will come in handy when we learn about some neat tricks next. Comment out PHP Code Blocks Check the following code <?php //* Toggle line if ( 1 ) {      // } else {      // } //*/ //* Toggle line if ( 2 ) {      // } else {      // } //*/ Now see how easy it is to toggle a part of PHP code by just removing or adding a single " / " from th

Introduction to Operator Overloading in C++

a1 = a2 + a3; The above operation is valid, as you know if a1, a2 and a3 are instances of in-built Data Types . But what if those are, say objects of a Class ; is the operation valid? Yes, it is, if you overload the ‘+’ Operator in the class, to which a1, a2 and a3 belong. Operator overloading is used to give special meaning to the commonly used operators (such as +, -, * etc.) with respect to a class. By overloading operators, we can control or define how an operator should operate on data with respect to a class. Operators are overloaded in C++ by creating operator functions either as a member or a s a Friend Function of a class. Since creating member operator functions are easier, we’ll be using that method in this article. As I said operator functions are declared using the following general form: ret-type operator#(arg-list); and then defining it as a normal member function. Here, ret-type is commonly the name of the class itself as the ope