Generating images in PHP using gd-library


I employed this technology when I was given the project of generating gift certificates from a template.

To begin, you should get a clean template (jpg, png, gif e.g. format). It should have high resolution if it’s going to be printed.


$template = "templates/gift_template.jpg";

Note: be careful with paths to images and fonts.

$im = imagecreatefromjpeg($template);

In this example I used imagecreatefromjpeg() function. You can use such functions as imagecreatefromgif(), imagecreatefrompng (), imagecreatefromwbmp(), e.g. for appropriate image format.

Next, if you are going to use true type fonts, they should be copied to your project folder.

To use different font colors, you should allocate all of them. To do that, you can use imagecolorallocate($image, $r,$g,$b) function, where $image is your template, 
$r,$g,$b – numbers for rgb color construction,
$darkGrey = imagecolorallocate($im, 35, 31, 32);
$orange = imagecolorallocate($im, 244, 117, 33);

To set text on image, you should use:

imagettftext ($image, $size, $angle, $x, $y, $color,
 $fontfile, $text), 

$image – your template,
$size – font-size,
$angle – angle of the font,
$x – x-coordinate on a template
$y – y-coordinate on an image
$color – your color, allocated before
$fontfile – path to your ttf font
$text – text, which will be displayed.


imagettftext($im, 70, 0, 940, 520, $darkGrey, $font_path,
imagettftext($im, 70, 0, 940, 660, $darkGrey, $font_path, $sender_name);
imagettftext($im, 40, 0, 940, 800, $darkGrey, $font_path, date('M j / Y',time()));
imagettftext($im, 50, 0, 940, 935, $orange, $font_path, '$' .$amount);
imagettftext($im, 50, 0, 1410,935, $orange, $font_path, $token);

To save your image, use the following function:

imagejpeg ($image, $filename = null, $quality = null),

$image is your created image,
$filename – path to the created file,
$quality – image quality (from 0 to 100)

There are analog functions:

imagegif ($image, $filename = null),
imagewbmp ($image, $filename = null, $foreground = null),
imagepng ($image, $filename = null, $quality = null, $filters = null)

They are almost the same, but be careful with the quality. This parameter is different for each type.
Now, your created image is ready. It’s stored in $filename. To destroy the temporary image after manipulations, use imagedestroy($im).

This is one of the simplest examples of how to generate images, using PHP. But it’s a great place to start.

See also:  Fancy jQuery Plugin