In web development, image manipulation is a common requirement — for example, cropping a specific area or resizing images for display optimization. PHP’s built-in GD library provides a variety of functions that make these tasks simple. This article will walk you through how to crop and resize images in PHP using GD, with practical examples included.
Cropping refers to extracting a specific region from an image. In PHP, this can be done easily using the GD library functions.
First, use imagecreatefromjpeg() or imagecreatefrompng() to load the original image resource:
$sourceImage = imagecreatefromjpeg('original.jpg');
Next, create a target image that will store the cropped result. Use imagecreatetruecolor() to create a new image resource:
$width = imagesx($sourceImage);
$height = imagesy($sourceImage);
$targetImage = imagecreatetruecolor($width, $height);
Use imagecopy() to copy a selected part of the source image into the target image. The following example extracts the central area of the original image:
$targetX = 0;
$targetY = 0;
$sourceX = $width / 4;
$sourceY = $height / 4;
$targetWidth = $width / 2;
$targetHeight = $height / 2;
$sourceWidth = $width / 2;
$sourceHeight = $height / 2;
imagecopy($targetImage, $sourceImage, $targetX, $targetY, $sourceX, $sourceY, $targetWidth, $targetHeight);
Finally, save the cropped image using imagejpeg():
imagejpeg($targetImage, 'cropped.jpg');
That’s it — you’ve successfully cropped an image using PHP.
Resizing an image means changing its dimensions based on a specific ratio or fixed width and height. The GD library makes resizing just as straightforward as cropping.
Once again, open the source image using imagecreatefromjpeg():
$sourceImage = imagecreatefromjpeg('original.jpg');
Determine the target width and height based on the desired scale factor:
$scale = 0.5; // Scale down by half
$targetWidth = imagesx($sourceImage) * $scale;
$targetHeight = imagesy($sourceImage) * $scale;
Use imagecreatetruecolor() to create a new blank image with the desired dimensions:
$targetImage = imagecreatetruecolor($targetWidth, $targetHeight);
Use imagecopyresampled() to scale the original image into the new size:
imagecopyresampled($targetImage, $sourceImage, 0, 0, 0, 0, $targetWidth, $targetHeight, imagesx($sourceImage), imagesy($sourceImage));
Save the resized version using imagejpeg() or imagepng():
imagejpeg($targetImage, 'resized.jpg');
This tutorial explained how to crop and resize images using PHP’s GD library, from loading the original image and creating a target image to performing the actual crop or resize and saving the result. The GD library makes it easy to perform essential image manipulation tasks, allowing developers to efficiently handle image processing needs within their web projects.