doufu4333
doufu4333
2011-09-07 11:27

如何使用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();
?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dragon202076 dragon202076 10年前

    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;
    }
    
    点赞 5 评论 复制链接分享

相关推荐