Maison  >  Article  >  développement back-end  >  Comment puis-je ajouter des filigranes aux images à l’aide de PHP ?

Comment puis-je ajouter des filigranes aux images à l’aide de PHP ?

DDD
DDDoriginal
2024-10-18 14:03:30219parcourir

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:

  • imagecreatefrompng() - Loads the watermark image as a PNG
  • imagecreatefromjpeg() - Loads the original image to be watermarked as a JPEG
  • imagecopy() - Copies the watermark image onto the original image

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>

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn