简体   繁体   中英

Adding watermark in PHP

I have made a bespoke CMS for a customer....

In the admin section, he adds photos for profiles of workers....

I need to add watermarks to all photos that admin uploads....

It can't be done as he uploads them (or, at least what I understand is that the image must be on the server BEFORE apply php/GD functions to it ?)... So it needs to be applied to images on their way out of the database...

foreach($get_all_photos_profile_array AS $get_photos_profile_each)
{
    echo "<img class=\"profile_photo\"src=\"$get_photos_profile_each\" alt=\"profile image\" width=\"270px\" height=\"405px\"/>";
}

This is what it would be without adding watermark....outputting all images for that particular profile....

I have tried replacing the stuff inside the loop with:

$stamp = imagecreatefrompng('stamp.png');
$im = imagecreatefromjpeg('photo.jpg');

$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($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);

Where stamp.png is the watermark and photo.jpg is the ... you get it.

I have spent sometime trying different things, but no luck...

How do I place 'imagepng($im)' in the echo statement so that it does it for each photo?

Also, is the header really important? struggling to rearange the code so that it is sent at the start of the file...

I think what you are aiming for is:

<img src="addWatermark.php?image=photo.jpg">

Then put all your watermark code in addWatermark.php and change the file loading to:

$im = imagecreatefromjpeg($_GET['image']);

The header is indeed important.

As it's a CMS, ideally you only want to run the watermark code once on each image when it gets uploaded - and then save that new watermarked image to a separate file:-

$output_filename="path/to/savedfile.png";
imagepng($im,$output_filename);
imagedestroy($im);

Then you'll need to store the watermarked filename somewhere, and whenever you want to display the watermarked version of that image, simply output some html referencing the image you just saved:-

echo "<img class=\"profile_photo\"src=\"".$output_filename."\" alt=\"profile image\" width=\"270px\" height=\"405px\"/>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM