Installing and Using GD Library with PHP

How to install the GD library and use it to write text to an image.

1363 views
d

By. Jacob

Edited: 2020-05-30 10:26

The GD library makes it possible to work with images in PHP, but it might need to be installed separately in order to work. If you are using a Ubuntu or Debian based Linux distribution, this is fairly straight forward using apt install, but you need to make sure to install the package that corresponds with your PHP version.

To find out your PHP version, type the following in your terminal:

php -v

In general, you will often be able to guess the package name, since there is a system to it; at least there is with PHP related packages. For example, to install GD library, you would try something like:

sudo apt install php7.4-gd

If you are using PHP 7, you may instead need to type:

sudo apt install php70-gd

Note. You may also search for the right package. This is done with apt-cache search php7

Once the GD package is installed you should also restart your server:

sudo service apache2 restart

Writing some text to an image

To see if the GD library was properly installed, we can try to create an image containing a simple text string.

To create the image, we use the imagecreate function, while adding the text itself is done with the imagestring function.

The imagecolorallocate is used to add the colors used in our image. Note that the first call to this function sets the background color.

// Create a 300*100 image
$img = imagecreate(300, 100);

// Backround and Text color
imagecolorallocate($img, 243, 243, 243);
$textcolor = imagecolorallocate($img, 33, 33, 33);

// Writa the text at given coordinates
imagestring($img, 5, 120, 40, 'Beamtic', $textcolor);

// Output the image
header('Content-type: image/png');

imagepng($img);
imagedestroy($img);
exit();

If CAPTCHAS is your thing, then you now have a solid starting point to create a basic CAPTCHA system that does not rely on third party services.

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials