PHP Image Processing (GD Library)
In this page:
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
echo extension_loaded('gd') ? "GD library available" : "GD not installed";
?>
Login to try C/C++/Java/PHP code in the editor
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
$image = imagecreatetruecolor(100, 100);
echo "Canvas created: " . imagesx($image) . "x" . imagesy($image);
imagedestroy($image);
?>
Login to try C/C++/Java/PHP code in the editor
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
$image = imagecreatetruecolor(100, 100);
$color = imagecolorallocate($image, 255, 0, 0);
imagerectangle($image, 10, 10, 90, 90, $color);
echo "Rectangle drawn on canvas";
imagedestroy($image);
?>
Login to try C/C++/Java/PHP code in the editor
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
$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);
?>
Login to try C/C++/Java/PHP code in the editor
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
$image = imagecreatetruecolor(50, 50);
imagepng($image, "output.png");
echo file_exists("output.png") ? "Saved to output.png" : "Save failed";
imagedestroy($image);
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: