我剛剛通過在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格式的透明背景水印圖片。
非常感謝您的回覆,我的代碼工作得很好,當我測試了「imagick」驅動程序出現問題後,我發現它工作正常。不過,我在我的項目中使用它。 – Shifrin