drwj4061 2016-10-25 11:02
浏览 59
已采纳

使用imagettftext的水印文本

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:

Image

Update:

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

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, "
", 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);
 }

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

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

  • 写回答

1条回答 默认 最新

  • doudiyu1639 2016-10-31 11:06
    关注

    Solution:

    $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);
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 51单片机使lcd显示器开机闪烁预设字符闪烁3次需要加什么代码
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥15 想用@vueuse 把项目动态改成深色主题,localStorge里面的vueuse-color-scheme一开始就给我改成了dark,不知道什么原因(相关搜索:背景颜色)
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥100 如何用js写一个游戏云存档
  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题