当文本大小未知时,在图像上将水印文本居中 [英] Center watermark text on image when unknown size of text
问题描述
我正在尝试创建一个带有水印文本的图像,并且希望它在图像上居中.我要加水印的文本可以是5个字符到15个字符,因此我不能为文本添加最终大小以适合每张图像.
I'm trying to create an image with a watermark text in it and I want it to be central on the image. The text I want to watermark can be anywhere from 5 characters to 15 characters, therefore I cannot put a final size for the text to fit every image.
这是我用来创建带水印图像的代码
This is the code I use to create the watermarked image
function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) {
list($width, $height) = getimagesize($SourceFile);
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($SourceFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$font = '../fonts/proxima-nova-light.otf';
$font_size = 100;
imagettftext($image_p, $font_size, 0, 303, 190, $black, $font, $WaterMarkText);
if ($DestinationFile<>'') {
imagejpeg ($image_p, $DestinationFile, 100);
} else {
header('Content-Type: image/jpeg');
imagejpeg($image_p, null, 100);
};
imagedestroy($image);
imagedestroy($image_p);
};
这在某些文本上做得很好,但是当我在较长的文本上尝试时,它看起来很糟糕.
Which does an excellent job on some texts but when I try it on longer texts it looks bad.
我想-以某种方式-计算文本的最佳大小,然后从中选择大小x和y.
I want to - somehow - calculate the optimal size of text and choose size, x and y from there.
有什么想法吗?
推荐答案
在@Sammitch的帮助下进行了一些研究之后,我终于知道了.这是工作代码:
After doing some research with help from @Sammitch I was able to figure it out. Here is the working code:
<?php
function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) {
$font = 'fonts/your-font-here.ttf';
$font_size = 40;
list($width, $height) = getimagesize($SourceFile);
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($SourceFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$bbox = imagettfbbox($font_size, 0, $font, $WaterMarkText);
$x = $bbox[0] + (imagesx($image) / 2) - ($bbox[4] / 2) + 10;
$y = $bbox[1] + (imagesy($image) / 2) - ($bbox[5] / 2) - 5;
imagettftext($image_p, $font_size, 0, $x, $y, $black, $font, $WaterMarkText);
if ($DestinationFile<>'') {
imagejpeg ($image_p, $DestinationFile, 100);
} else {
header('Content-Type: image/jpeg');
imagejpeg($image_p, null, 100);
};
imagedestroy($image);
imagedestroy($image_p);
};
?>
这篇关于当文本大小未知时,在图像上将水印文本居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!