Image Processing in PHP Using GD Library

This article provides a practical guide on how to process and manipulate images in PHP using the built-in GD library. You will learn how to verify the GD installation, load images from various formats, perform essential manipulations like resizing and cropping, apply basic filters, and save or output the final image files.

Enabling the GD Library

Before manipulating images, you must ensure the GD extension is enabled in your PHP environment. Open your php.ini file and locate the following line:

;extension=gd

Remove the semicolon (;) to uncomment and enable it:

extension=gd

Restart your web server (such as Apache or Nginx) to apply the changes. You can verify if GD is enabled by running phpinfo() or checking extension_loaded('gd') in a PHP script.

The Basic Image Manipulation Workflow

The workflow for processing images with GD always follows four basic steps: 1. Load an existing image file or create a blank canvas. 2. Manipulate the image (resize, crop, rotate, or add text). 3. Output the image to the browser or save it to a directory. 4. Destroy the image resource to free up server memory.


Loading and Creating Images

To work on an existing image, load it using the function corresponding to its file format:

$jpegImage = imagecreatefromjpeg('source.jpg');
$pngImage  = imagecreatefrompng('source.png');
$gifImage  = imagecreatefromgif('source.gif');
$webpImage = imagecreatefromwebp('source.webp');

To create a new, blank canvas from scratch, use imagecreatetruecolor():

// Create a blank 400x300 pixel canvas
$canvas = imagecreatetruecolor(400, 300);

// Allocate a color (RGB: Red, Green, Blue)
$white = imagecolorallocate($canvas, 255, 255, 255);

// Fill the canvas with the color
imagefill($canvas, 0, 0, $white);

Resizing and Scaling Images

To resize an image, the easiest method in PHP 5.5+ is using the imagescale() function, which automatically handles aspect ratios.

$source = imagecreatefromjpeg('photo.jpg');

// Scale the image to a width of 300px (height is calculated automatically)
$resized = imagescale($source, 300);

// Save the scaled image
imagejpeg($resized, 'resized_photo.jpg');

// Free memory
imagedestroy($source);
imagedestroy($resized);

For more precise control, such as resizing a specific portion of an image into another, use imagecopyresampled():

$source = imagecreatefromjpeg('photo.jpg');
$srcWidth = imagesx($source);
$srcHeight = imagesy($source);

$dstWidth = 150;
$dstHeight = 150;

$destination = imagecreatetruecolor($dstWidth, $dstHeight);

// Copy and resize the entire source image into the destination canvas
imagecopyresampled(
    $destination, $source, 
    0, 0, 0, 0, 
    $dstWidth, $dstHeight, $srcWidth, $srcHeight
);

imagejpeg($destination, 'thumbnail.jpg', 90); // 90 is the JPEG quality percentage

imagedestroy($source);
imagedestroy($destination);

Cropping Images

You can crop images using the imagecrop() function by defining a bounding box array containing the x, y, width, and height of the crop area.

$source = imagecreatefrompng('avatar.png');

// Define the cropping area
$cropArea = [
    'x' => 50,
    'y' => 50,
    'width' => 200,
    'height' => 200
];

$cropped = imagecrop($source, $cropArea);

if ($cropped !== false) {
    imagepng($cropped, 'cropped_avatar.png');
    imagedestroy($cropped);
}

imagedestroy($source);

Adding Text to Images

To add text or watermarks to an image, use imagettftext() to render TrueType fonts.

$image = imagecreatefromjpeg('banner.jpg');

// Allocate text color (White)
$textColor = imagecolorallocate($image, 255, 255, 255);

// Path to a valid TrueType font (.ttf) file on your server
$fontPath = __DIR__ . '/fonts/Roboto-Bold.ttf'; 

// Add text: (image, size, angle, x, y, color, font, text)
imagettftext($image, 20, 0, 10, 50, $textColor, $fontPath, "Watermark Text");

imagejpeg($image, 'watermarked_banner.jpg');
imagedestroy($image);

Rotating and Applying Filters

GD provides functions to rotate images and apply basic filters like grayscale, brightness adjustments, or blurs.

Rotating an Image

$image = imagecreatefromjpeg('original.jpg');

// Rotate by 90 degrees counter-clockwise with a black background fill
$rotated = imagerotate($image, 90, 0);

imagejpeg($rotated, 'rotated.jpg');
imagedestroy($image);
imagedestroy($rotated);

Applying Grayscale Filter

$image = imagecreatefromjpeg('color.jpg');

// Apply grayscale effect
imagefilter($image, IMG_FILTER_GRAYSCALE);

imagejpeg($image, 'grayscale.jpg');
imagedestroy($image);

Outputting Directly to the Browser

If you want to display the generated image dynamically in a web browser instead of saving it as a file, send the correct HTTP header and omit the file path parameter from the output function.

$image = imagecreatetruecolor(200, 200);
$red = imagecolorallocate($image, 255, 0, 0);
imagefill($image, 0, 0, $red);

// Send content-type header
header('Content-Type: image/png');

// Output the image directly to the browser output buffer
imagepng($image);

// Free memory
imagedestroy($image);