An Introduction to GD Library

Jan 7, 2008 15:47 GMT  ·  By

Images can be processed using specialized softwares which are available for any operating system. On the Internet, images can be manipulated dynamically with the help of server side programming languages.

PHP (Hypertext Preprocessor) allows you to create, process and output images in web browsers. In order to be able to manage images using PHP code, the PHP version must be compiled with GD graphics library. If you want to find out details about your version of GD library or if GD support exists, call phpinfo() function or GD_VERSION (only available as of PHP 5.2.4) from within a simple PHP script.

The GD library is coded in C programming language and provides "wrappers" for PHP and many other languages. The image functions present in this library helps you to dynamically generate images (PNG, JPEG), thumbnails, apply filters to images and more.

Let's consider for example the next script in order to demonstrate the execution of image processing actions with the help of PHP code and GD library:

[CODE=0][CODE=1]

The PHP header function determines the correct HTTP header type and, as a consequence, the web browser will render the script output as an image file. The imagedestroy() function is used to destroy the image loaded in the server memory in order to free the occupied memory.

The imagecreatefrompng () function will open the test.png image and the new image resource obtained will be contained in the variable $img. The imagefilter function is used to apply different filters to the image. In the example considered IMG_FILTER_GRAYSCALE and IMG_FILTER_BRIGHTNESS filters were used.

The first filter converts the image to grayscale and the second one changes the brightness to a specified level value (10 in this case). You can adjust the parameter value to see the image changes in browser output. Based on this script, you can also try to discover other functions available for image processing in PHP that you can include in your own scripts.