Working with Images in PHP: Overview of GD and Imagick Libraries
Image processing is one of the common tasks in web development. PHP has two main libraries for working with graphics: GD (built-in) and Imagick (a wrapper over ImageMagick). In this article, we will explore their capabilities, installation, and practical examples.
GD Library
GD is a standard PHP extension available on most hosting platforms. It allows you to create, modify, and save images in JPEG, PNG, GIF, and WEBP formats.
Installation
On Ubuntu/Debian:
sudo apt install php-gdsudo systemctl restart apache2On Windows — uncomment the line extension=gd in php.ini.
Key GD Functions
imagecreatefromjpeg(),imagecreatefrompng()— loading an imageimagesx(),imagesy()— getting width and heightimagecopyresampled()— resampling with scalingimagefilter()— applying filters (blur, negate)imagettftext()— text with TrueType fontimagejpeg(),imagepng()— saving the result
Example 1: Resizing an Image
<?php$src = 'photo.jpg';$dest = 'thumb.jpg';$newWidth = 300;
// Load the source image$img = imagecreatefromjpeg($src);$width = imagesx($img);$height = imagesy($img);
// Calculate the new height proportionally$newHeight = intval($height * $newWidth / $width);
// Create a new image$thumb = imagecreatetruecolor($newWidth, $newHeight);imagecopyresampled($thumb, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// Saveimagejpeg($thumb, $dest, 85);imagedestroy($img);imagedestroy($thumb);echo "Done: $dest";?>Example 2: Applying a Watermark
<?php$mainImg = imagecreatefromjpeg('background.jpg');$watermark = imagecreatefrompng('logo.png');
// Get dimensions$mW = imagesx($mainImg);$mH = imagesy($mainImg);$wW = imagesx($watermark);$wH = imagesy($watermark);
// Position — bottom right corner with a 10px margin$dstX = $mW - $wW - 10;$dstY = $mH - $wH - 10;
// Copy the watermark with transparencyimagecopy($mainImg, $watermark, $dstX, $dstY, 0, 0, $wW, $wH);
// Saveimagepng($mainImg, 'result.png');imagedestroy($mainImg);imagedestroy($watermark);?>Imagick Library
Imagick is an object-oriented wrapper over the powerful ImageMagick tool. It supports over 200 formats, complex transformations, working with PDFs, animation, and color profiles.
Installation
sudo apt install imagemagick php-imagicksudo systemctl restart apache2Verify installation:
<?php phpinfo(); ?>Look for the imagick section.
Key Classes and Methods
Imagick— main class for working with imagesreadImage()— loading a fileresizeImage()— resizingcropImage()— croppingcompositeImage()— overlaying imagesblurImage()— blurringsetImageFormat()— format conversion
Example 3: Scaling and Cropping
<?php$image = new Imagick('photo.jpg');
// Scale to 800x600, maintaining proportions$image->resizeImage(800, 600, Imagick::FILTER_LANCZOS, 1, true);
// Crop the central 400x400 area$width = $image->getImageWidth();$height = $image->getImageHeight();$x = ($width - 400) / 2;$y