如何使用文本为图像添加水印?

时间:2016-08-05 11:37:23

标签: php text watermark

所以我有一些代码可以对目录中的所有文件进行处理,对它们进行水印并将它们放入另一个目录中。我想知道如何用文字对我的图像进行水印,我尝试使用imagettftext(),但没有运气。

这是工作代码

<?php
//Source folder where all images are placed
$source="myimages";

//Destination folder where all images with watermark will be copied
$destination="donewatermarks";

//Creating an image object of watermark image
$watermark=imagecreatefrompng("watermark.png");

//Margin of watermark from right and bottom of the main image
$margin_right=10;
$margin_bottom=10;

//Height ($sy) and Width ($sx) of watermark image
$sx=imagesx($watermark);
$sy=imagesy($watermark);

//Get list of images in source folder
$images=array_diff(scandir($source), array('..', '.'));

foreach($images as $image){
//Create image object of main image
$img=imagecreatefromjpeg($source.'/'.$image);

//Copying watermark image into the main image
imagecopy($img, $watermark, imagesx($img) - $sx - $margin_right, 
imagesy($img) - $sy - $margin_bottom, 0, 0, $sx, $sy);

//Saving the merged image into the destination folder
imagejpeg($img, $destination.'/'.$image,100);

//Destroying the main image object
imagedestroy($img);
}

//Destroying watermark image object
imagedestroy($watermark);

?>

提前致谢!

这是我尝试的代码,它当前返回错误

<?php
//Source folder where all images are placed
$source="watermarkitems";

//Destination folder where all images with watermark will be copied
$destination="donewatermarks";

//Creating an image object of watermark image
$watermark=imagecreatefrompng("watermark.png");

//Margin of watermark from right and bottom of the main image
$margin_right=10;
$margin_bottom=10;

//Height ($sy) and Width ($sx) of watermark image
$sx=imagesx($watermark);
$sy=imagesy($watermark);

$text = 'Testing...';

//Get list of images in source folder
$images=array_diff(scandir($source), array('..', '.'));

foreach($images as $image){
//Create image object of main image
$img=imagecreatefromjpeg($source.'/'.$image);

// Add the text
imagettftext($img, 20, 0, 10, 20, $black, $font, $text);

//Saving the merged image into the destination folder
imagejpeg($img, $destination.'/'.$image,100);

header('Content-Type: image/jpg');

//Destroying the main image object
imagedestroy($img);
}

//Destroying watermark image object
imagedestroy($watermark);

?>

1 个答案:

答案 0 :(得分:0)

此代码运行,您可以尝试使用此代码。

<?php
$watermark = imagecreatefrompng('watermark.png');
$imageURL = imagecreatefrompng('bg.png');
$watermarkX = imagesx($watermark);
$watermarkY = imagesy($watermark);
imagecopy($imageURL, $watermark, imagesx($imageURL)/5, imagesy($imageURL)/5, 0, 0, $watermarkX, $watermarkY);
header('Content-type: image/png');
imagepng($imageURL);
imagedestroy($imageURL);
?>