Dynamic image creation using PHP

Dynamic image creation with PHP: Part II

On page 1 we looked at how PHP can be used to generate images dynamically. Now we will explore a few more advanced features of the PHP GD image extension.

PostScript fonts

PostScript fonts are very widely used and were purpose built for software development. The quality of fonts available and their sheer variety make them a must for anyone interested in graphics development.

The Type1 Font library (t1lib) is used by the PHP Image extension to provide PostScript font functionality to developers. The t1lib package comes with several free fonts included. They can be found in the t1lib-1.3.1/Fonts/Type1/ directory of the unpacked archive.

Executing the following script will generate the 'Hello World' image. Notice how the fonts change from top to bottom.

01 <?
02 header("Content-type: image/jpeg");
03 $fontdir = '/home/swm/t1lib-1.3.1/Fonts/type1/';
04 $handle = opendir($fontdir);
06 $fonts = array();
07 $maxwidth = 0;
08 $str = "Hello World";
09 $fontsize = 30;
10 $spacing = $fontsize + 10;
12 while(($file = readdir($handle)) !== false) {
13    if(!is_file($fontdir.$file))
14    continue;
15  $font = imagepsloadfont($fontdir.$file);
16  if(!$font)
17    continue;
19   list($x1,$y1,$x2,$y2) = imagepsbbox($str,$font,$fontsize,0,0,0);
21    if($maxwidth < $x2)
22    $maxwidth = $x2;
23   $fonts[] = $font;
24 }
26 $im = imagecreate($maxwidth +40,(count($fonts) * $spacing) + ($spacing - $fontsize));
27 $black = Imagecolorallocate($im, 0, 0, 0);
28 $white = Imagecolorallocate($im, 255, 255, 255);
29 $x = 20;
30 $y = 0;
31 for($i=0;$i<count($fonts);$i++) {
32   imagepstext($im,$str,$fonts[$i],$fontsize,$white,$black,$x,$y + $spacing);
33   $y += $spacing;
34   imagepsfreefont($fonts[$i]);
35 }
36 ImageJpeg($im, "", 100);
37 ImageDestroy ($im);
38 ?>

Now for the script itself. First, we set the Content Type header so that Web browsers understand that the content is an image. The third line sets the variable $fontdir to a directory containing fonts (change this to the location of the t1lib fonts on your system).

Line eight sets the string the script will be printing - 'Hello World' - while lines nine and 10 register the font size and line spacing in pixels, respectively.

The script then loops through the files in $fontdir, being careful on line 13 to avoid entries other than files and those that are not PostScript fonts in .pbf format (the only format supported). The font is then loaded: imagepsloadfont(). We do this here so that we can measure the width of the string $str using this font, because we need this information in order to generate a palette large enough to ensure that no strings will be truncated.

The script measures the width of the string using the imagepsbbox() routine which returns an array whose elements are, in order, the lower left x- and y-coordinates and the upper right x- and y-coordinates. Using the upper right x-coordinate is sufficient for measuring the horizontal width of the text drawn in the particular font. This width is then compared to the running largest width encountered ($maxwidth). If the width of the current string is longer than that of the previous maximum, then $maxwidth is replaced with the new width. Finally, the script adds the font handle $font to an array of fonts, $fonts.

Line 26 generates the new palette, $im. The width is $maxwidth plus 40 pixels - for padding. The height is 40 pixels times the number fonts. We also add the difference between the height of a line space (40 pixels) and that of the font size (30 pixels) to give the effect of padding at the bottom of the image.

Finally, the script iterates through the list of fonts and draws the text on the image using imagepstext(). The last two arguments to imagepstext() are the lower left x- and y-coordinates where the text is to begin. For each iteration, we advance the y-coordinate (line 33). The 34th line also frees the loaded font from the extension. The PostScript library can be quite memory intensive.

Finally, line 36 outputs the image in JPEG format with 100 per cent image quality.

Join the PC World newsletter!

Error: Please check your email address.

Our Back to Business guide highlights the best products for you to boost your productivity at home, on the road, at the office, or in the classroom.

Keep up with the latest tech news, reviews and previews by subscribing to the Good Gear Guide newsletter.

Gavin Sherry

PC World
Show Comments

Most Popular Reviews

Latest News Articles


PCW Evaluation Team

Azadeh Williams

HP OfficeJet Pro 8730

A smarter way to print for busy small business owners, combining speedy printing with scanning and copying, making it easier to produce high quality documents and images at a touch of a button.

Andrew Grant

HP OfficeJet Pro 8730

I've had a multifunction printer in the office going on 10 years now. It was a neat bit of kit back in the day -- print, copy, scan, fax -- when printing over WiFi felt a bit like magic. It’s seen better days though and an upgrade’s well overdue. This HP OfficeJet Pro 8730 looks like it ticks all the same boxes: print, copy, scan, and fax. (Really? Does anyone fax anything any more? I guess it's good to know the facility’s there, just in case.) Printing over WiFi is more-or- less standard these days.

Ed Dawson

HP OfficeJet Pro 8730

As a freelance writer who is always on the go, I like my technology to be both efficient and effective so I can do my job well. The HP OfficeJet Pro 8730 Inkjet Printer ticks all the boxes in terms of form factor, performance and user interface.

Michael Hargreaves

Windows 10 for Business / Dell XPS 13

I’d happily recommend this touchscreen laptop and Windows 10 as a great way to get serious work done at a desk or on the road.

Aysha Strobbe

Windows 10 / HP Spectre x360

Ultimately, I think the Windows 10 environment is excellent for me as it caters for so many different uses. The inclusion of the Xbox app is also great for when you need some downtime too!

Mark Escubio

Windows 10 / Lenovo Yoga 910

For me, the Xbox Play Anywhere is a great new feature as it allows you to play your current Xbox games with higher resolutions and better graphics without forking out extra cash for another copy. Although available titles are still scarce, but I’m sure it will grow in time.

Featured Content

Latest Jobs

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?