水印:在图像的多个部分显示相同的文本


Watermarking: Display the same text on multiple parts of the image

我想在图像中添加文本。文本应显示在图像的多个区域(而不仅仅是一个区域)。

例如,我想用文本堆栈加水印。堆栈应在图像的不同区域显示至少 8 次。

我刚刚了解了imagestring()imagettftext(),但这两个只在一个地方显示我的文字。

图像不是固定大小,所以我无法提前指定确切和多个位置。它应该适用于所有大小的图像

<?php
/*
image.php
*/
header("Content-type: image/jpeg");
$imgPath = 'olximage.jpg';
$image = imagecreatefromjpeg($imgPath);
$color = imagecolorallocate($image, 255, 255, 255);
$string = "stack overflow";
$fontSize = 3;
$x = 15;
$y = 185;
imagestring($image, $fontSize, $x, $y, $string, $color);
$x = 15;
$y = 175;
imagestring($image, $fontSize, $x, $y, $string, $color);
imagejpeg($image);
?>

提前致谢

例如:

<?php
/*
image.php
*/
header("Content-type: image/jpeg");
$imgPath = 'olximage.jpg';
$image = imagecreatefromjpeg($imgPath);
$color = imagecolorallocate($image, 255, 255, 255);
$string = "stack overflow";
$fontSize = 3;
$imageHeight = imagesy($image);
$distanceY = 10;
$maxImageStrings = max(8, $imageHeight / $distanceY);
$x = 15;    
for ($i = 0; $i < $maxImageStrings; $i++) {
    $y = $i * $distanceY;
    imagestring($image, $fontSize, $x, $y, $string, $color);
}
imagejpeg($image);

您可以根据需要微调计算。

我正在使用Imagick扩展。如果您想这样做,请遵循详细信息:

.PHP:

// Create objects
$image = new Imagick('image.png');
$watermark = new Imagick();
// Watermark text
$text = 'Copyright';
// Create a new drawing palette
$draw = new ImagickDraw();
$watermark->newImage(140, 80, new ImagickPixel('none'));
// Set font properties
$draw->setFont('Arial');
$draw->setFillColor('grey');
$draw->setFillOpacity(.5);
// Position text at the top left of the watermark
$draw->setGravity(Imagick::GRAVITY_NORTHWEST);
// Draw text on the watermark
$watermark->annotateImage($draw, 10, 10, 0, $text);
// Position text at the bottom right of the watermark
$draw->setGravity(Imagick::GRAVITY_SOUTHEAST);
// Draw text on the watermark
$watermark->annotateImage($draw, 5, 15, 0, $text);
// Repeatedly overlay watermark on image
for ($w = 0; $w < $image->getImageWidth(); $w += 140) {
    for ($h = 0; $h < $image->getImageHeight(); $h += 80) {
        $image->compositeImage($watermark, Imagick::COMPOSITE_OVER, $w, $h);
    }
}
// Set output image format
$image->setImageFormat('png');
// Output the new image
header('Content-type: image/png');
echo $image;

尽管在 ImageMagick 网站上可以找到大量命令行示例,但这就是我们将开始的地方。