在PHP中的图像上添加文本的字体路径问题

时间:2019-07-11 04:23:15

标签: php

使用以下代码,一切都很好,除了font_path之外,还可以在图像上添加文本。

<?php
  //Set the Content Type
  header('Content-type: image/jpeg');

  // Create Image From Existing File
  $jpg_image = imagecreatefromjpeg('sunset.jpg');

  // Allocate A Color For The Text
  $white = imagecolorallocate($jpg_image, 255, 255, 255);

  // Set Path to Font File
  $font_path = 'arial.TTF';

  // Set Text to Be Printed On Image
  $text = "This is a sunset!";

  // Print Text On Image
  imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text);

  // Send Image to Browser
  imagejpeg($jpg_image);

  // Clear Memory
  imagedestroy($jpg_image);
?>

我尝试过

$font_path = 'arial.TTF';
$font_path = '/arial.TTF';
$font_path = './arial.TTF';
$font_path = '../arial.TTF';

等。然后将arial.ttf放到脚本的所有文件夹中。它仅适用于此src:

$font_path = 'C:\xampp\htdocs\app\arial.TTF';

当然,此路径不适合我的网站。

我该如何解决?还是您有更好的解决方案来在php中的图像上添加文本?​​

1 个答案:

答案 0 :(得分:0)

尝试以下类似方法。

// When the font file is in the same directry as your php file
$font_path = __DIR__ . '/arial.TTF';

// When the font file is in the parent directry of your php file
$font_path = dirname(__DIR__) . '/arial.TTF'