使用imagettftext的水印文本 [英] Watermark text using imagettftext

查看:171
本文介绍了使用imagettftext的水印文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将水印(来自输入的文字)添加到.jpg图像(来自输入)并定义位置,它适用于一行但更多 - 开始向左移动:

I am trying to add watermark (text from input) to .jpg image (from input) and define position, it's fine for one line but for more - starts moving to the left:

更新:

echo $the_box["width"] - 1132,
echo $the_box["height"] - 25

但我的形象是1024x768。

but my image is 1024x768.

if (isset($_POST['TextToUpload'])) {
   $im = imagecreatefromjpeg($target_file);//jpg. to add watermark(text)

$font = 'Roboto-Black.ttf'; // font path
$font_size = 25;
$font_color =  imagecolorresolvealpha($im, 255, 255, 255,$tr1);//tr1 - var to define % of opacity
$text = $wt;// wt - text from input  $wt = $_POST['TextToUpload'];  
$lines = explode('|', wordwrap($text, 15, "\n", true)); //15 sumbols - line limit

$text_angle=0;//var for angle
$text_padding    = 10; //some padding
$imageX = imagesx($im)+ $text_padding;
$imageY = imagesy($im)+ $text_padding;
$the_box        = calculateTextBox($text, $font, $font_size, $text_angle);
$y=$the_box["top"] + ($imageY / 2) - ($the_box["height"] / 2);
$x=$the_box["left"] + ($imageX / 2) - ($the_box["width"] / 2);

foreach ($lines as $line){    
imagettftext($im, $font_size, 0, $x, $y, $font_color, $font, $line);
// Increment Y so the next line is below the previous line
@$y += 23;}

imagepng($im, $target_file);
imagedestroy($im);
 }

我发现了很多关于此问题的信息,但使用 imagecreate()

I found lot of info about this issue but using imagecreate().

function calculateTextBox:
http://php.net/manual/en/function.imagettfbbox.php#105593

function calculateTextBox: http://php.net/manual/en/function.imagettfbbox.php#105593

推荐答案

解决方案:

$wt_len = strlen($text);//char count
$lc=1;// num lines
if ($wt_len > 15 && $wt_len <= 30) {
      $lc=2;
  } if ($wt_len > 30 && $wt_len <= 45) {
      $lc=3;
  } if ($wt_len > 45 && $wt_len <= 60) {
      $lc=4;
  }

foreach ($lines as $line){


$y=$the_box["top"] + ($imageY / 2) - ($the_box["height"] / 2);
$x=$the_box["left"] + ($imageX / 2) - ($the_box["width"] / (2*$lc));// * num lines to get width of 1 line

imagettftext($im, $font_size, 0, $x, $y, $font_color, $font, $line);

}

这篇关于使用imagettftext的水印文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆