PHP GD Library将文本写入图像

问题描述 投票:1回答:4

您好以下answer,我正在尝试使用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()函数我得到以下内容:

GDINFO

关于可能发生什么的任何想法?

php gd
4个回答
1
投票

完成以下步骤:

  • 如果您正在使用基于Unix的操作系统检查'denmark.ttf'文件的权限。确保您的php脚本可以访问它
  • 更改字体路径如下:$font_path = './denmark.ttf';

0
投票

获取解决方案,检查此代码。

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);
?>

0
投票

$ font_path我遇到了一些奇怪的问题。

所以阅读http://php.net/manual/en/function.imagettftext.php

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

  putenv('GDFONTPATH=' . realpath('.'));
  $font_path = 'denmark.ttf';

现在工作正常。

我还测试了Roman提供的解决方案,只需将font_path更改为:

$font_path = './denmark.ttf';

脚本运行正常!

谢谢你的帮助!


0
投票
$font_path = 'denmark.ttf';

应该

$font_path = 'denmark';   //no need to incluce .ttf when not using backward slash.
© www.soinside.com 2019 - 2024. All rights reserved.