重复水印php

Shi*_*rin 4 php watermark image-manipulation

我在一个项目中使用Intervention Image图像处理库这个库,并且我一直坚持在整个源图像上添加水印图像。

是否可以在整个源图像上重复水印图像,如下例所示?

库存照片-79576145-旧房间

我尝试以下代码,但它对我不起作用。

$thumbnail = $manager->make($name);
$watermark = $manager->make($watermarkSource);
$x = 0;

while ($x < $thumbnail->width()) {
    $y = 0;

    while($y < $thumbnail->height()) {
        $thumbnail->insert($watermarkSource, 'top-left', $x, $y);
        $y += $watermark->height();
    }

    $x += $watermark->width();
}

$thumbnail->save($name, 80);
Run Code Online (Sandbox Code Playgroud)

Mik*_*oot 8

我刚刚通过在 Laravel 框架中使用干预图像库解决了这个问题。这是代码片段。

public function watermarkPhoto(String $originalFilePath,String $filePath2Save ){

    $watermark_path='photos/watermark.png';
    if(\File::exists($watermark_path)){

        $watermarkImg=Image::make($watermark_path);
        $img=Image::make($originalFilePath);
        $wmarkWidth=$watermarkImg->width();
        $wmarkHeight=$watermarkImg->height();

        $imgWidth=$img->width();
        $imgHeight=$img->height();

        $x=0;
        $y=0;
        while($y<=$imgHeight){
            $img->insert($watermark_path,'top-left',$x,$y);
            $x+=$wmarkWidth;
            if($x>=$imgWidth){
                $x=0;
                $y+=$wmarkHeight;
            }
        }
        $img->save($filePath2Save);

        $watermarkImg->destroy();
        $img->destroy(); //  to free memory in case you have a lot of images to be processed
    }
    return $filePath2Save;
}
Run Code Online (Sandbox Code Playgroud)

如果您使用 7 之前的 PHP 版本,请从函数参数中删除 String 类型声明。就做到了

    public function watermarkPhoto($originalFilePath, $filePath2Save ){....}
Run Code Online (Sandbox Code Playgroud)

另外,如果您不使用 Laravel 框架并且没有包含 File 类,只需从函数中删除冗余和检查。

      if(\File::exists($watermark_path))
Run Code Online (Sandbox Code Playgroud)

因此,最简单的与框架无关的函数是:

function watermarkPhoto($originalFilePath, $filePath2Save ){

        $watermark_path='photos/watermark.png';
        $watermarkImg=Image::make($watermark_path);
        $img=Image::make($originalFilePath);
        $wmarkWidth=$watermarkImg->width();
        $wmarkHeight=$watermarkImg->height();

        $imgWidth=$img->width();
        $imgHeight=$img->height();

        $x=0;
        $y=0;
        while($y<=$imgHeight){
            $img->insert($watermark_path,'top-left',$x,$y);
            $x+=$wmarkWidth;
            if($x>=$imgWidth){
                $x=0;
                $y+=$wmarkHeight;
            }
        }
        $img->save($filePath2Save);

        $watermarkImg->destroy();
        $img->destroy();

    return $filePath2Save;
}
Run Code Online (Sandbox Code Playgroud)

您还需要具有透明背景的 png 格式的水印图像。

  • 非常感谢您的回复,我的代码工作得很好,当我测试时,“imagick”驱动程序有问题,后来我发现它工作得很好。尽管如此,我仍在我的项目中使用它。 (2认同)