【问题标题】:How to add text to an image with PHP GD library如何使用 PHP GD 库向图像添加文本
【发布时间】:2012-10-27 09:33:42
【问题描述】:

我在 image_creator 中有图像创建代码。

<?php
header("Content-Type: image/jpeg");
$im = ImageCreateFromGif("photo.gif"); 
$black = ImageColorAllocate($im, 255, 255, 255);
$start_x = 10;
$start_y = 20;
Imagettftext($im, 12, 0, $start_x, $start_y, $black, 'verdana.ttf', "text to write");
Imagejpeg($im, '', 100);
ImageDestroy($im);
?> 

图片输出文件为image.php,代码如下

<html>
<head>
</head>
<body>
    <img src="http://localhost/image_creator.php"/> 
</body>

</html>

当我运行 image.php 时,我只是得到一个空白页。为什么会这样?

【问题讨论】:

  • 首先$black = ImageColorAllocate($im, 255, 255, 255); - 这是白色的,不是黑色的。你有任何错误吗?检查错误日志?
  • @iMoses 我认为$black 只是因为他从php.net 复制代码:php.net/manual/en/function.imagettftext.php
  • 不正确或没有意义。我相信他们做对了。这不是问题,只是令人困惑。 “空白”图像可能只是白色背景上的白色。
  • 我从白色变成了黑色,但还是同样的问题!!我认为 Imagettftext 找不到“verdana.ttf”文件,虽然所有内容都在同一个文件夹中..
  • 然后尝试将字体文件指定为./verdana.ttf。

标签: php html image gd


【解决方案1】:

使用它向图像添加文本(复制自PHP for Kids)

<?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 = 'font.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);
?>

【讨论】:

  • 你刚刚从phpforkids.com/php/php-gd-library-adding-text-writing.php粘贴它尝试指出问题而不是
  • 请同时引用您的来源...否则只是抄袭。我已在引文中添加。
  • 如果我想在发送到浏览器之前在同一张图片上添加几行文本,是否需要添加几个imagettftext() 函数?另外,如何将此图像保存到服务器中的实际目录中,以便用户可以随时打印?
  • 由于某种原因代码不适用于 png,当然要更改文件和函数名称
【解决方案2】:

这里的问题是, $black = ImageColorAllocate($im, 255, 255, 255); //

$black = ImageColorAllocate($im, 0, 0, 0);

【讨论】:

    猜你喜欢
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    相关资源
    最近更新 更多