PHP supports the GD Graphics Libarary which,
created by Thomas Boutell, provides support for the creation, and even
the management of .jpg and .png images. Unfortunately, due to licensing
problems, the latest version does not support .gif images.
Creating Images
PHP supports the GD
Graphics Libarary which, created by Thomas Boutell, provides support
for the creation, and even the management of .jpg and .png images.
Unfortunately, due to licensing problems, the latest version does not
support .gif images.
This library allows you to generate images dynamically through your scripts.I am going to assume the use of GD1.3, which is the latest version that
supports .gif images.
The function, ImageCreate() is used to actually create the
image - although you can use ImagePng(), ImageJpeg()
or ImageGif() depending on the setup you have on your system.
This script will create an .gif file:
<?php
header("Content-type: image/gif"); $img = ImageCreate(100,20);
$red = ImageColorAllocate($img, 255, 0, 0); $white =
ImageColorAllocate($img, 255, 255, 255);
ImageString($img, 3, 3, 3, "Uh, this is an image!", $white);
ImageGif($img);
ImageDestroy($im);
?>
Now, an explanation of each line:
-
header("Content-type: image/gif"); - This tells the
browser that the image is a .gif file.
-
$img = ImageCreate(100,20); - This creates the GD image so
that it can be used by any of the GD functions. However, the fact that we
are creating a .gif file is not determined until we actually tell the
script that it is a .gif at the end.
-
$red = ImageColorAllocate($img, 255, 0, 0); - This creates a
red background colour.
-
$white = ImageColorAllocate($img, 255, 255, 255); - This
creates a white foreground colour.
-
ImageString($img, 3, 3, 3, "Uh, this is an image!", $white);
- This creates a string telling the GD to use a built in font at x-pixel
location of 3 and a y-pixel location of 3. The colour of this is white and
the actual text of "Uh, this is an image!".
-
ImageGif($img); - Actually creates the image and displays it
in the browser for the user to see.
-
ImageDestroy($im); - Although this is done anyway by the GD,
it specifically clears the memory used to create the .gif and is good
practise to include.
In addition to just creating an image on the fly and then losing it, you can
save the image for use later. This can be done with the following modified
script:
<?php
$filename = "image.gif";
$img = ImageCreate(100,20);
$red = ImageColorAllocate($img, 255, 0, 0); $white =
ImageColorAllocate($img, 255, 255, 255);
ImageString($img, 3, 3, 3, "Uh, this is an image!", $white);
ImageGif($img, $filename);
ImageDestroy($im);
?>
This will save the image created as a file so you can then retrieve it using
the normal HTML <img> tag.
|