PHP Programming/Images

Introduction
PHP can create and modify dynamically some images, for example with the, included by default since PHP 3.0.

A new image creation must follow with a few steps:
 * 1) Memory loading of a new or an existing image.
 * 2) Optional colors loading to add.
 * 3) Optional components modifications (lines creation, points, fillings, texts addition...).
 * 4) Image restitution by posting its type into the header.
 * 5) Memory release.

Create a new image
To create an image ex nihilo, use the function: which creates in memory a new image, its height and width are defined in pixel, and restitutes a reference to the new image.

There is also another function for this, but it's not recommended as its colors amplitude is worst :

To load in memory an image which had been saved on the disk:

Example:

Other function: which creates an image from its text format, specified in parameter.

If an error occurs, theses functions return.

Work with the colors
To allocate a color, the parameters must be defined:

To define a transparency into a PNG:

where  is the result of.

It's also possible possible to determine the transparency, between 0 and 127 (which represents the total transparency) with the function:

Remark: the first allocated color defines the whole image background.

Once the image is created and colored, it becomes possible to apply the following operations to it:
 * Draw some pixels (eg: create lines).
 * Work on the existing pixels by designating zones.

Draw shapes
To draw a pixel, we use its coordinates (x, y below):

To draw a line between two points:

To create a rectangle from its diagonal:

To represent an ellipse from its center, its height and width:

or by precising its arc by its angles in gradient (clockwise numbered):

Rework the existing pixels
The most used functions to rework images like photos, is certainly, which allows to copy a rectangular zone to paste it in another image. Example:

where:
 * is the source image;
 * is the destination image;
 * are the coordinates of ;
 * are the coordinates of, beginning at the top left;
 * are the source and destination rectangles widths and heights.

It becomes understandable after, that if  is equal to , and   to  , the image rectangular portion will remain the same size. On the contrary we lengthen or enlarge.

The function  receives the same parameters as , but in case of resizing, the quality est improved.

Then it exists the function  which allow numerous effects, such as grayscale, relief, or recoloration.

Print the output
The obtained image format ("png", "jpeg" or "gif") can be specified by the function called, via the content-type (by default text/html) with:

To visualize the image after, place it in parameter in a function depending on its type:,   or.

Then, liberate the memory with. This stage is optional but strongly recommended for huge images.

Example
The following code displays in the navigator, a 50 pixels red square into a 100 black one.