Welcome to our PHP GD Library tutorial! This lesson is designed for beginners and intermediate learners, so let's dive into the world of PHP graphics with ease and practical examples.
The PHP GD Library is a PHP extension for handling and manipulating graphics. It provides functions for creating and editing images, making it a powerful tool for creating dynamic graphics in your web applications.
php -i | grep -i gdIf it's installed, you'll see the GD info. If not, you'll need to recompile PHP with the GD extension.
Let's create a simple image using PHP GD Library.
<?php
// Create a new image
$image = imagecreatetruecolor(200, 200);
// Set the background color
$background_color = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $background_color);
// Output the image
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>This script creates a 200x200 white image and outputs it as a PNG image.
<?php
$source_image = imagecreatefromjpeg('source.jpg');
$new_image = imagecreatetruecolor(100, 100);
imagecopyresampled($new_image, $source_image, 0, 0, 0, 0, 100, 100, imagesx($source_image), imagesy($source_image));
header('Content-Type: image/jpeg');
imagejpeg($new_image);
imagedestroy($source_image);
imagedestroy($new_image);
?>This script resizes a JPEG image named 'source.jpg' to 100x100 pixels.
<?php
$source_image = imagecreatefromjpeg('source.jpg');
$watermark_image = imagecreatefrompng('watermark.png');
$source_width = imagesx($source_image);
$source_height = imagesy($source_image);
$watermark_width = imagesx($watermark_image);
$watermark_height = imagesy($watermark_image);
$watermark_x = $source_width - $watermark_width - 10;
$watermark_y = $source_height - $watermark_height - 10;
imagecopy($source_image, $watermark_image, $watermark_x, $watermark_y, 0, 0, imagesx($watermark_image), imagesy($watermark_image));
header('Content-Type: image/jpeg');
imagejpeg($source_image);
imagedestroy($source_image);
imagedestroy($watermark_image);
?>This script adds a watermark to a JPEG image named 'source.jpg'.
What is the PHP GD Library used for?
Happy coding, and keep learning with CodeYourCraft! π