2016-06-09 67 views
0

我正在使用Intervention Image圖像操作庫這個庫在一個項目中,我堅持在源圖像上添加水印圖像。重複水印php

是否有可能在整個源圖像上重複水印圖像,如下例所示?

stock-photo-79576145-old-room

我嘗試下面的代碼,但它並沒有爲我工作。

$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); 

回答

1

我剛剛通過在Laravel Framework中使用干涉圖像庫解決了這個問題。所以這裏是代碼片段。

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; 
} 

如果您使用7之前的PHP版本,請從函數參數中移除String類型聲明。只是使它

public function watermarkPhoto($originalFilePath, $filePath2Save){....} 

此外,如果你不使用Laravel框架和你沒有File類包括的只是從功能刪除redundand檢查。

 if(\File::exists($watermark_path)) 

所以最簡單的架構無關的功能是:

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; 
} 

而且你需要在png格式的透明背景水印圖片。

+0

非常感謝您的回覆,我的代碼工作得很好,當我測試了「imagick」驅動程序出現問題後,我發現它工作正常。不過,我在我的項目中使用它。 – Shifrin