To watermark images using PHP, you can use the GD Library, which is a graphics library bundled with PHP. Here’s a basic PHP code example to add a watermark to an image:
here are the steps on how to create watermark images using PHP:
- Create a PHP script. The script will need to include the following functions:
imagecreatefromjpeg()
: This function creates a new image from a JPEG file.imagecopy()
: This function copies part of one image to another image.imagejpeg()
: This function saves an image to a file.imagedestroy()
: This function destroys an image resource.
- Load the original image and the watermark image. The original image is the image that you want to watermark. The watermark image is the image that you want to overlay on the original image.
- Set the position of the watermark image. You can use the
imagecopy()
function to position the watermark image anywhere on the original image. The following code shows how to position the watermark image in the top-left corner of the original image:
$x = 0;
$y = 0;
imagecopy($im, $watermark, $x, $y, 0, 0, imagesx($watermark), imagesy($watermark));
- Save the watermarked image. Use the
imagejpeg()
function to save the watermarked image to a file. - Destroy the image resources. Use the
imagedestroy()
function to destroy the image resources for the original image and the watermark image.
Another example is here with an explanation;
In this example, we assume that the source image is a JPEG, and the watermark is a PNG image with transparency. The addWatermark function takes four parameters:
- $sourceImagePath: The path to the source image that you want to watermark.
- $watermarkImagePath: The path to the watermark image that will be added to the source image.
- $outputImagePath: The path where the watermarked image will be saved.
- $positionX (optional): The X-coordinate position of the watermark from the top-left corner of the source image.
- $positionY (optional): The Y-coordinate position of the watermark from the top-left corner of the source image.
You can adjust the $positionX and $positionY values to control the position of the watermark on the source image. Additionally, you may modify the function to handle other image formats or apply different watermarking effects based on your requirements.