1 min read

PHP GD Library (Image Processing)

The GD Library allows you to define, draw, and manipulate images dynamically using PHP. It is commonly used for creating CAPTCHAs, resizing uploaded images, or generating charts.


1. Creating an Image

You can create a blank canvas or create an image from an existing file.

// Create a 200x200 blank image
$image = imagecreatetruecolor(200, 200);

// Or create from existing file
// $image = imagecreatefromjpeg("photo.jpg");

2. Allocating Colors

Before drawing, you need to allocate colors. The first color allocated becomes the background color for palette-based images, but for true color images, you must fill the background manually.

$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$red   = imagecolorallocate($image, 255, 0, 0);

// Fill background with white
imagefill($image, 0, 0, $white);

3. Drawing Shapes and Text

PHP provides various functions to draw on the canvas.

// Draw a black line
imageline($image, 0, 0, 200, 200, $black);

// Draw a red rectangle
imagefilledrectangle($image, 50, 50, 150, 150, $red);

// Write a string (Font size 1-5)
imagestring($image, 5, 60, 90, "Hello GD!", $white);

4. Outputting the Image

You can either save the image to a file or output it directly to the browser.

// Output to browser
header("Content-Type: image/png");
imagepng($image);

// OR Save to file
// imagepng($image, "my_image.png");

5. Cleaning Up

Always destroy the image resource to free up memory.

imagedestroy($image);

programming/php/php programming/php/php-file-uploads