subject: Create Thumbnail With GD [print this page] As a compliment to the amazing iMagick extension which allows an easy method to create thumbnails from images, this example shows how to create a thumbnail image using the GD library that is bundled with PHP. The script also takes into account the dimensions of the image and maintains the original aspect ratio to avoid any distortion.
In this example, the image is a JPG but other formats can be used in the same manner with imageCreateFromGif and imageGif etc. Note the use of imageCopyResampled to give better image quality than imageCopyResized.
Abstract
PHP comes with the GD graphics library bundled making for a ready to use graphics tool. However, web developers have demanded more quality and performance that GD has traditionally been able to provide. Several attempts were made at providing Image Magick support for PHP, until Mikko Koppanen set to the task to provide a comprehensive extension called Imagick which provides a feature rich object oriented interface to the Image Magick library.
Installation
The Imagick extension can be compiled directly into PHP or as a shared library. As it is a PECL extension, it can simply be installed with the following command line.
pecl install imagick
Following installation from PECL this line needs to be added to the php.ini file.
extension=imagick.so
With the Imagick extension installed, the system is now right for image creation, processing, and manipulation.
In the code above, a non-existent file has been specified and passed directly to the Imagick constructor. Rather than spitting out an error, the Imagick library comes complete with several exception classes and so, throws an exception that needs to be caught in a catch block. Lets re-run this code, with an image that exists.