PHP GD库将文本写入图像

PHP GD库将文本写入图像,php,gd,Php,Gd,您好,接下来,我正在尝试使用GD库向图像添加文本,遗憾的是,我无法做到这一点,这是我的代码: <?php //Set the Content Type header('Content-type: image/jpeg'); // Create Image From Existing File $jpg_image = imagecreatefromjpeg('serra.jpg'); // Allocate A Color For The Text $whit

您好,接下来,我正在尝试使用GD库向图像添加文本,遗憾的是,我无法做到这一点,这是我的代码:

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


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

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

  // Set Path to Font File
  $font_path = 'denmark.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);
?> 

此代码将输出不包含文本的图像。

serra.jpg和denmark.ttf文件与脚本位于同一文件夹中

在我的服务器上运行gd_info()函数,我得到以下结果:


关于可能发生的事情有什么想法吗?

要找到解决方案,请检查此代码

imagejpeg($jpg_image,'newimage.jpeg');
您无法保存图像

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


  // Create Image From Existing File
  $source="mk.jpg";
  $jpg_image = imagecreatefromjpeg($source);

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

  // Set Path to Font File
  $font_path = 'ASMAN.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,'newimage.jpeg');

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

执行以下步骤:

  • 如果您在基于Unix的操作系统中工作,请检查
    'dankman.ttf'
    文件。确保您的php脚本可以访问它
  • 按如下方式更改字体路径:
    $font_path='./denmark.ttf'

我在$font\u路径上遇到了一些奇怪的问题

因此,阅读

我看到我必须添加putenv。。。在$font_path变量之前,如下所示:

  putenv('GDFONTPATH=' . realpath('.'));
  $font_path = 'denmark.ttf';
现在一切正常

我还测试了Roman提出的解决方案,只需将字体路径更改为:

$font_path = './denmark.ttf';
剧本写得很好

谢谢你们的帮助

$font_path = 'denmark.ttf';
应该是

$font_path = 'denmark';   //no need to incluce .ttf when not using backward slash.

$font\u路径是否存在?使用
file\u exists()
检查是否存在。是,如果(!file\u exists($font\u path)){die(“No font”);}运行,则不会返回任何结果。所以我相信这个文件确实存在。
serra.jpg
的维度是什么?你确定文本的坐标没有超出图像范围吗?serra.jpg是2272x1704,我对文本的位置进行了调整,以确定这是否是问题所在,但是没有运气。@André你检查过这个了吗?你可以把你的字体放在同一个文件夹里,从同一个目录调用它。我注意到一件事,你没有生成新的图像,只是暂时发送到浏览器