【问题标题】:PHP GD Library write text to imagePHP GD 库将文本写入图像
【发布时间】:2016-05-14 10:45:55
【问题描述】:

您好,关注此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() 函数我得到以下信息:

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

【问题讨论】:

  • $font_path 存在吗?使用file_exists() 进行检查。
  • 是的,运行 if(!file_exists($font_path)) { die("No font"); },什么也没返回。所以我相信该文件确实存在。
  • serra.jpg 的尺寸是多少?您确定文本的坐标不在图像之外吗?
  • serra.jpg 是 2272x1704,我确实玩过文本的位置,看看是否是问题所在,但没有运气。
  • @André 你检查了吗imagetext

标签: php gd


【解决方案1】:
$font_path = 'denmark.ttf';

应该是

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

【讨论】:

    【解决方案2】:

    $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';
    

    脚本运行良好!

    感谢大家的帮助!

    【讨论】:

    • 你可以把你的字体放在同一个文件夹里,从同一个目录调用它
    • 我注意到一件事你并没有生成你只是临时发送到浏览器的新图像
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      执行以下步骤:

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

      【讨论】:

        猜你喜欢
        • 2012-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-01
        • 1970-01-01
        • 2012-10-27
        相关资源
        最近更新 更多