Home >Backend Development >PHP Tutorial >How Can I Add Watermarks to Images Using PHP?
Add Watermarks to Images Using PHP
If you're working on a website that allows users to upload images, you may need to add a watermark to those images to protect them from unauthorized use. Adding a watermark ensures that your logo or branding is visible on every uploaded image. Here's how you can achieve this in PHP:
Using PHP Functions
The PHP manual provides a comprehensive example using the following functions:
Positioning the Watermark
To position the watermark effectively, you can specify the margins using the $marge_right and $marge_bottom variables. This allows you to control the distance between the watermark and the edges of the original image.
Outputting the Watermarked Image
Once the watermark has been added, you can output the watermarked image using the header() function to set the content type to PNG. Then, use imagepng() to output the image and imagedestroy() to free up the memory used.
Example Code
Here's an example code snippet:
<code class="php">// Load the stamp and the photo to apply the watermark to $stamp = imagecreatefrompng('stamp.png'); $im = imagecreatefromjpeg('photo.jpeg'); // Set the margins for the stamp and get the height/width of the stamp image $marge_right = 10; $marge_bottom = 10; $sx = imagesx($stamp); $sy = imagesy($stamp); // Copy the stamp image onto our photo using the margin offsets and the photo // width to calculate positioning of the stamp. imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp)); // Output and free memory header('Content-type: image/png'); imagepng($im); imagedestroy($im);</code>
The above is the detailed content of How Can I Add Watermarks to Images Using PHP?. For more information, please follow other related articles on the PHP Chinese website!