Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I repeat a watermark throughout a requested image using PHP?

I'm trying to add watermark to all the images in a directory, let's say www.example.com/private. Some of these images have massive resolutions, while others are relatively normal so at the moment my watermark is working fine for the smaller images. Even by centering the watermark, I'm still leaving desirable sections of the bigger images vulnerable to cropping.

So my question is how would I go about writing a php script to repeat the watermark throughout the image, both vertically and horizontally? I don't really know enough about back-end development except that I know it's required to provide adequate watermarking protection, so I've been looking around on google and could only find this http://www.regardadesign.co.uk/blog/post/php-image-manipulation/15, which doesn't work.

So far I've placed the following .htaccess file into the /private directory:

<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule \.(gif|jpeg|jpg|png)$ /admin/watermark.php [QSA,NC]
</ifModule>"

And this is the script in watermark.php file:

<?php
ini_set('memory_limit','200M');
$path = $_SERVER['DOCUMENT_ROOT'].$_SERVER['REQUEST_URI'];
$image = imagecreatefromstring(file_get_contents($path));
$w = imagesx($image);
$h = imagesy($image);
$watermark = imagecreatefrompng('watermark.png');
$ww = imagesx($watermark);
$wh = imagesy($watermark);
imagecopy($image, $watermark, (($w/2)-($ww/2)), (($h/2)-($wh/2)), 0, 0, $ww, $wh);
header('Content-type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);
exit();
?>
like image 541
Ben Avatar asked Dec 05 '25 01:12

Ben


1 Answers

This is happening because you are inserting the watermark only once. If you repeat the watermark along the image area it will do the trick.

Replace your imagecopy line for this:

$img_paste_x = 0;
while($img_paste_x < $w){
    $img_paste_y = 0;
    while($img_paste_y < $h){
        imagecopy($image, $watermark, $img_paste_x, $img_paste_y, 0, 0, $ww, $wh);
        $img_paste_y += $wh;
    }
    $img_paste_x += $ww;
}
like image 154
v42 Avatar answered Dec 07 '25 16:12

v42