In website development, image processing is a common requirement. Often, we need to add watermarks or text to images for copyright protection or to convey additional information. As a powerful server-side scripting language, PHP provides rich image handling features. This article will guide you through how to easily add watermarks and text to images using PHP.
Adding a watermark is a common way to protect an image's copyright. Below is an example of how to add a watermark to an image using PHP's GD library:
<?php // Create canvas and open image $image = imagecreatefromjpeg('image.jpg'); $watermark = imagecreatefrompng('watermark.png'); // Get the width and height of the image and watermark $imageWidth = imagesx($image); $imageHeight = imagesy($image); $watermarkWidth = imagesx($watermark); $watermarkHeight = imagesy($watermark); // Calculate watermark position $positionX = $imageWidth - $watermarkWidth - 10; // 10 pixels from the right $positionY = $imageHeight - $watermarkHeight - 10; // 10 pixels from the bottom // Copy watermark onto image imagecopy($image, $watermark, $positionX, $positionY, 0, 0, $watermarkWidth, $watermarkHeight); // Output image header('Content-Type: image/jpeg'); imagejpeg($image); // Release memory imagedestroy($image); imagedestroy($watermark); ?>
In this example, we first create a canvas and open the image and watermark files. We then use PHP's `imagesx()` and `imagesy()` functions to get the width and height of the image and watermark, which helps in calculating the position for the watermark. Finally, we use `imagecopy()` to overlay the watermark on the image and output the final image using `imagejpeg()`.
In addition to watermarks, many developers want to add custom text to images. PHP provides the `imagettftext()` function, which makes this task straightforward. Below is an example of adding text to an image:
<?php // Create canvas and open image $image = imagecreatefromjpeg('image.jpg'); // Set text color $textColor = imagecolorallocate($image, 255, 255, 255); // Set font $font = 'arial.ttf'; // Set text $text = 'Hello, World!'; // Add text imagettftext($image, 30, 0, 10, 50, $textColor, $font, $text); // Output image header('Content-Type: image/jpeg'); imagejpeg($image); // Release memory imagedestroy($image); ?>
In this example, we create a canvas and open the target image. We then use `imagecolorallocate()` to set the text color and `imagettftext()` to add the text to the image. After that, we output the image with `imagejpeg()`, and finally, we use `imagedestroy()` to release memory.
By using PHP's GD library, we can easily add watermarks and text to images. These techniques help us protect the copyright of images and add extra information. We hope this article helps you in your image handling tasks.