Outputting Text

To output text using PHP, you first need fonts. PHP allows you to use TrueType (TTF) fonts, PostScript Type 1 (PS) fonts, or FreeType 2 fonts, with TTF tending to be the most popular, due to the availability of fonts. If you are running Windows, you probably have at least 20 TTF fonts already installed that you can use—check in the "Fonts" subdirectory of your Windows directory to see what is available. Many Unix distributions come with TTF fonts installed also—either check in /usr/share/fonts/truetype, or run a search for them. Alternatively, if you have a Windows CD around, you can borrow some from there. Some distributions (including Debian and SUSE) allow you to install Microsoft's Core Fonts for the Web. The Free Software Foundation has a set of free fonts that you can grab from its web site.

For this next example, I used the font Arial, which is stored in the same directory as my PHP script. Save this code as addingtext.php:

    $image = imagecreate(400,300);
    $blue = imagecolorallocate($image, 0, 0, 255);
    $white = ImageColorAllocate($image, 255,255,255);

    if(!isset($_GET['size'])) $_GET['size'] = 44;
    if(!isset($_GET['text'])) $_GET['text'] = "Hello, world!";

    imagettftext($image, $_GET['size'], 15, 50, 200, $white,
            "ARIAL", $_GET['text']);
    header("content-type: image/png");
    imagepng($image);
    imagedestroy($image);

The two isset() lines in that example are there to make sure there is a default font size, 44, and default text, "Hello, world!" for our image. These are ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.