Generating Images with PHP

A set of php functions exists for generation of image files. These were developed by Thomas Boutell and are called GD (Gif Draw). When PHP is compiled with GD, these functions are available to create or modify images.

A function called gd_info() gives a modicum of information about the capabilities of the GD/php build in use. Click here for a demonstration.

Other information on the GD functions is available at php.net or Zend or Boutell.com

Overview of Steps in Image Generation

  1. Create the image.
  2. Allocate the colors to be used.
  3. Draw something.
  4. Set the mime type.
  5. Output the image.

Here is an example:

<?php
//----------- create image --------------
$im=imageCreate(250,250);
//----------allocate colors -------------
$white=imageColorAllocate($im,0xff,0xff,0xff);
$gray=imageColorAllocate($im,0xcc,0xcc,0xcc);
$black=imageColorAllocate($im,0x00,0x00,0x00);
//--- draw 2 circles, a dot, and some text ---
imagefilledEllipse($im,51,125,10,10,$gray);
imageEllipse($im,125,125,148,148,$black);
imageSetPixel($im,125,125,$black);
imagestring($im, 5, 10,230, 'hydrogen', $black); 
//----------- set mime type -------------
header('Content-Type: image/gif');
//------------ output image -------------
imageGIF($im);
?>

This image was sent directly to the browser, as a php file with the code:

<img src="H.php">
The browser knows to interpret it as an image, because the header function declares it to be of mime type image/gif. The output function imageGIF() must agree with the header function.

The image file must contain no errors. If it does, the image will not display. No other warning will be given. Parsing errors will not be detected.

Image Generation Considered in More Detail

Image Creation
FunctionArgumentsUsage
imagecreate(x,y) Creates new palette based image
imagecreatetruecolor(x,y) Creates new true color image. Prefers GD 2.0.28 or later.
imagecreatefromgd('filename') Creates new image from GD file.
imagecreatefromgif('filename') Creates new image from .gif file.
imagecreatefromjpeg('filename') Creates new image from .jpg file. Requires GD 1.8 or later.
imagecreatefrompng('filename') May create new image from .png file. Check User Contributed Notes at php.net.
imagedestroy(image) Does not destroy image. Frees memory used in its creation.

All the imagecreate() functions take two integer arguments, x and y, representing the image width and height in pixels.

All return a resource representing the image.

Color Allocation
FunctionArgumentsUsage
imagecolorallocate(image, r,g,b) Allocates a color for an image.
imagecolorallocatealpha(image, r,g,b,alpha) Allocate a color for an image. Alpha sets the degree of 'transparency' allowed. Ranges from 0 to 127.
imagepalettecopy(destination image,source image) Copy the palette from source image to destination image.

image is an image resource returned from a call to one of the imagecreate() functions. r,g,b are bytes, denoting red, green, blue color.

The first call to imagecolorallocate() sets the background color for the image.

Drawing and Adding Text
Drawing:

The top left corner is (0,0).

imagesetpixel(image, x,y, color) Draws a single pixel at point (x,y).
imageline(image, x1,y1,x2,y2,color) Draw a line from (x1,y1) to (x2,y2).
imageellipse(image, xc,yc,width,height,color) Draw an ellipse, centered at (xc,yc).
imagefilledellipse(image, xc,yc,width,height,color) Draw a filled ellipse
imagearc(image, xc,yc, w,h, start,end, color) Draw a partial ellipse, beginning at start degrees, and going counterclockwise to end degrees.
imagefilledarc(image, xc,yc, w,h, start,end, color)
imagerectangle (image, x1,y1, x2,y2, color) Draw a rectangle with (x1,y1) and (x2,y2) at opposite corners.
imagefilledrectangle(image, x1,y1, x2,y2, color) Draw a filled rectangle
imagepolygon(image, xy, n, color) Draws a polygon of n vertices. xy is an array of all points in the form: (x1,y1,x2,y2,...xn,yn). n is the number vertices.
imagefilledpolygon(image, xy, n, color) Draw a filled polygon
imagefill(image, x, y, color ) Flood fill to from x,y to boundary.
imagefilltoborder(image, x, y, borderColor, color) Flood fill from x,y to borderColor
imagecolorat(image, x,y)Returns color at (x,y)
imagesetstyle(image, stylearray)stylearray is an array of colors to be used in line drawing.
imagesetthickness(image, thickness) Set the thickness for line drawing in pixels. Does not affect pixels or ellipses.
imagesettile(image, tileImage) Set the tile image for use by filling functions.

Adding Text:

FunctionArgumentsUsage
imagestring(image, font, x,y, 'string', color) Draw a string horizontally
imagestringup(image, font, x,y, 'string', color) Draw a string vertically
imagechar(image, font, x,y, 'string', color) Draw first character of string horizontally
imagecharup(image, font, x,y, 'string', color) Draw first character of string vertically
imageloadfont('fontfile') Loads a font for the above functions
Other Fonts for Adding Text

The function imagestring() uses a single font. This is available in 5 sizes, denoted by the integers, 1 to 5. However, it can use other fonts, if they are first introduced with the function imageloadfont('fontfile'). These fonts must be gdf fonts.

I have found two sources for gdf fonts.

  1. Dave Wedwick has created a routine which converts Windows ttf fonts to gdf fonts. It can be found in the User Contributed Notes for imageloadfont() at php.net.
  2. Some gdf fonts are available for free download at Widgnet.com.
<?php
$im=imageCreate(400,400);
$blue=imageColorAllocate($im,0xee,0xee,0xff);
$black=imageColorAllocate($im,0x00,0x00,0x00);
imageEllipse($im,200,200,212,212,$black);
imageEllipse($im,94,200,10,10,$black);
imageSetPixel($im,200,200,$black);
$fontfile="./fonts/arial14.gdf";
$font=imageloadfont($fontfile);

imagestring($im, $font, 10, 380, "Hydrogen", $black);
header('Content-Type: image/gif');
imageGIF($im);
?>

Set the Mime Type

The header function is used to set the mime type. For example, the header for a gif image would be:

header('Content-Type: image/gif');

The mime types needed for the other image types are:

type/subtype file extension(s)
image/gif gif
image/jpeg jpe, jpeg, jpg
image/pngpng
image/vnd.wap.wbmp wbmp
image/x-xbitmap xbm

A complete list of mime types and subtypes is available at W3C Mime Reference

The mime type must agree with the output function.

Output the Image

Output functions:

FunctionArgument(s)Usage
imagegif(image [,'filename']) Output GIF image to browser or file
imagejpeg(image [,'filename']) Output JPEG image to browser or file
imagepng (image [,'filename']) Output PNG image to browser or file
imagewbmp (image [,'filename']) Output WBMP image to browser or file
imagexbm (image [,'filename']) Output XBM image to browser or file
Output an image to a File rather than the Browser

The earlier example sent an image directly to the browser. No image file was created. Although the above method is simple, it is sometimes advantageous to actually create an image file, since image files are downloaded faster than the php file can be downloaded and interpreted. This is done by using the optional argument in the output function to name a file for the output.

The image must be called twice. The first time it is called as 'filename.php' since the php code must be invoked. The documentation says that an image will be seen in the browser, but I do not get one. Thereafter it can be called as 'filename.gif' (or whatever). An image will appear, and a '.gif' file will actually appear on the server.

More Useful PHP GD Functions

Determining Image Properties

In order to print out the results of these functions, you should open the image with one of the image create functions, but not use the header or output function.

<?php
 $filename='../snowflake/02c.gif';
 $im=imageCreateFromgif($filename);
 $t=imagecolorstotal($im);
 for ($i=0;$i<$t;$i++){
   $arr= imagecolorsforindex($im,$i);
   print_r($arr);
 };
?>

The file can then be called with an anchor link.

<pre>
<a href="exam.php">Find Image Colors</a>
</pre>

Find Image Colors

Copy an Image to another Image

imagecopy(dest, src, dx, dy, sx, sy, sw, sh)

Note: The entire color palette of the source image is copied as well.

Change an Image's Color

imagetruecolortopalette(image, dither, n)

changes truecolor image to palette based.

Apply a Filter to an Image
 imagefilter(image, filter [,arg1,arg2,arg3])

The argument filter can take on any of the values:

IMG_FILTER_NEGATE Reverses colors.
IMG_FILTER_GRAYSCALE Converts to grayscale.
IMG_FILTER_COLORIZE Like IMG_FILTER_GRAYSCALE, except color is specified with arg1, arg2 and arg3 (red green, blue)
IMG_FILTER_BRIGHTNESS Changes the brightness. arg1 sets level.
IMG_FILTER_CONTRAST Changes the contrast of the image. arg1 sets level.
IMG_FILTER_EDGEDETECT Uses edge detection to highlight the edges in the image.
IMG_FILTER_EMBOSS Embosses the image.
IMG_FILTER_GAUSSIAN_BLUR Blurs the image using the Gaussian method.
IMG_FILTER_SELECTIVE_BLUR Blurs the image.
IMG_FILTER_MEAN_REMOVAL Uses mean removal to achieve a "sketchy" effect.
IMG_FILTER_SMOOTH Smooths image. arg1 sets level.
Rotate Image

I've only been able to use this function to rotate an image in a file, not one I'm drawing.

<?php
$filename = 'elip.gif';
$degrees = 45;
header('Content-type: image/gif');
$source = imagecreatefromgif($filename);
$rotate = imagerotate($source, $degrees, 0);
imagegif($rotate,'rotate.gif',10);
?>

Make image transparent

imagecolortransparent(image, i)
Defines color i to be transparent.

Note from cinymini at php.net cinymini 14-Dec-2006 11:17 When you use palette images (created with imagecreate()), the first color allocated is the background color. This color cannot be used for transparency. So if you want to make the background transparent, first allocate a dummy background color, then allocate the real background color and declare this is as transparent.

Overlapping colors using imagecolorallocatealpha(). The code for this image is at Zend.