使用GD Lib添加文本

时间:2013-06-18 16:05:31

标签: php gd php-gd

我一直在用自己的头发撕掉我的头发并尝试了许多解决方案,但无济于事。

我正在尝试为图像添加一些文字,但它所做的只是显示我的背景图像,有什么明显的东西我在这里做错了吗?

感谢adcance

<?
header('Content-Type: image/jpeg');

$fbid = $_POST['fbid'];
$background_img = $_POST['background'];
$message = $_POST['text'];
$ts = $_POST['ts'];

$filename = $fbid . "-" . $ts . ".jpg";

$image_canvas = imagecreatetruecolor(640,400);

$background = imagecreatefromjpeg($background_img);
$overlay    = imagecreatefrompng("../images/image-overlay.png");

imagecopyresampled($background, $overlay, 0, 0, 0, 0, imagesx($overlay), imagesy($overlay), imagesx($overlay), imagesy($overlay));

imagefilledrectangle($image_canvas, 0,0,150,30, $background);

$white = imagecolorallocate($background, 255, 255, 255);

imagettftext($image_canvas, 25, 0, 50, 50, $white, "arial.TTF", $message);

imagejpeg($background,"../created/" . $filename, 100);

imagedestroy($background);

2 个答案:

答案 0 :(得分:0)

你错过了画布。使用imageCreateTrueColor开始构建。

$imageCanvas = imageCreateTrueColor($width, $height);
//your code
$background = imagecreatefromjpeg($background_img);
//more of your code
imagefilledrectangle($imageCanvas, 0, 0, 150, 30, $background);
//now do the same for the text only us imag
imagettftext($imageCanvas, 25, 0, 50, 50, $white, "arial.TTF", $message);

您合并$ imageCanvas上的jpeg和文本元素。

答案 1 :(得分:0)

看看这个。它工作正常,页面链接如下。根据您的原始帖子,我相信这就是您所寻找的。

 /* first composite the canvas with the background */
 $background_img="../img/adfuba_october.png";
 $compositeString = "composite.png";

 list($width,$height) = getimagesize($background_img);
 $image_canvas = imagecreatetruecolor($width,$height);
 $background = imagecreatefrompng($background_img);
 imagecopyresampled($image_canvas,$background,0,0,0,0,$width,$height,$width,$height);

 /* now add the text */
 $fontPath = "path/to/your/fontFile/ARIAL.TTF";
 $fontSize = 24;
 $percent = 0.25;
 $txt_x = abs($width*$percent);
 $txt_y = abs($height*$percent);
 $color = "008844";
 $message = "This is User Text";
 imageTTFtext($image_canvas, $fontSize, 0, $txt_y, $txt_y, $color, $fontPath, $message);

 /* now generate the file */
 imagepng($image_canvas, $compositeString, 0) or die("error saving png");

 ?>
 <p>This is a composite image:<br><img src="<?php echo $compositeString;?>"></p>

您可以看到合成图片here。 要记住几件事情。即使TrueType字体文件与脚本位于同一目录中,TrueType字体外观的路径也应该是绝对的。

此外,画布是您的背景对象,然后您将图像或文本分层到画布顶部。

最后,(你可能已经想到了这一点)你的分层元素依赖于顺序,从画布到文本。含义画布 - &gt;背景 - &gt;另一个图形 - &gt;然后是文字。否则,你最终可能会掩盖你想要在前面渲染的元素。希望有所帮助。