← Back to PHP Course | Chapter 16: Testing & Tools | Lesson 8 of 10

PHP Image Processing (GD Library)

Introduction to GD Library

The GD library is a PHP extension for creating and manipulating images programmatically -- resizing thumbnails, adding watermarks, or generating charts entirely on the server.

Example: Introduction to GD Library

php
<?php
echo extension_loaded('gd') ? "GD library available" : "GD not installed";
?>

Creating Canvas Surfaces

imagecreatetruecolor() allocates a blank canvas of a given width and height in memory, which becomes the surface you draw shapes, text, or loaded images onto before saving or outputting it.

Example: Creating Canvas Surfaces

php
<?php
$image = imagecreatetruecolor(100, 100);
echo "Canvas created: " . imagesx($image) . "x" . imagesy($image);
imagedestroy($image);
?>

Drawing Geometry

GD provides functions like imageline(), imagerectangle(), and imageellipse() for drawing basic shapes directly onto a canvas, which is the foundation for generating simple graphics like charts on the fly.

Example: Drawing Geometry

php
<?php
$image = imagecreatetruecolor(100, 100);
$color = imagecolorallocate($image, 255, 0, 0);
imagerectangle($image, 10, 10, 90, 90, $color);
echo "Rectangle drawn on canvas";
imagedestroy($image);
?>

Loading and Resizing

imagecopyresampled() loads an existing image and produces a resized copy with smooth interpolation, which is how you generate properly scaled thumbnails instead of oversized originals.

Example: Loading and Resizing

php
<?php
$src = imagecreatetruecolor(200, 200);
$thumb = imagecreatetruecolor(50, 50);
imagecopyresampled($thumb, $src, 0, 0, 0, 0, 50, 50, 200, 200);
echo "Thumbnail: " . imagesx($thumb) . "x" . imagesy($thumb);
imagedestroy($src);
imagedestroy($thumb);
?>

Saving Image Files

Once processing is done, imagejpeg() or imagepng() either saves the result to a file on disk or streams it straight to the browser, provided you send the matching Content-Type header first.

Example: Saving Image Files

php
<?php
$image = imagecreatetruecolor(50, 50);
imagepng($image, "output.png");
echo file_exists("output.png") ? "Saved to output.png" : "Save failed";
imagedestroy($image);
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.