当我尝试在 PHP + GD 库中添加图像时,文本消失了

Text is disappearing when I try to add an image in PHP + GD library

我正在尝试创建一个包含一些文本和缩放图片的 PNG。这是文本的代码,它工作正常:

<?php
session_start();
error_reporting(E_ALL);

$label = imagecreate(500, 500);
imagecolorallocate($label, 0, 0, 0);

// up text
$color = imagecolorallocate($label, 255, 255, 255);
imagettftext($label, 50, 0, 0, 150, $color, "arial.ttf", "UP UP UP");

// down text
$color = imagecolorallocate($label, 255, 255, 255);
imagettftext($label, 50, 0, 0, 350, $color, "assets/fonts/arial.ttf", "DOWN DOWN DOWN");

header('Content-type: image/png');
imagepng($label);
imagedestroy($label);
die();
?>

通过上面的代码得到下图,是正确的:

现在我想在其中放一张小图片,所以我从 JPEG 文件 (adidas.jpg) 加载图片。这是代码

<?php
session_start();
error_reporting(E_ALL);


$label = imagecreate(500, 500);
imagecolorallocate($label, 0, 0, 0);


// up text
$color = imagecolorallocate($label, 255, 255, 255);
imagettftext($label, 50, 0, 0, 150, $color, "arial.ttf", "UP UP UP");

// image
$src = imagecreatefromjpeg("adidas.jpg");
$pic = imagecreatetruecolor(500, 500);
imagecopyresampled($label, $src, 0, 0, 0, 0, 150, 150, imagesx($src), imagesy($src));
$white = imagecolorallocate($pic, 255, 255, 255);
imagefill($label,0,0,$white);
imagedestroy($pic);


// down text
$color = imagecolorallocate($label, 255, 255, 255);
imagettftext($label, 50, 0, 0, 350, $color, "arial.ttf", "DOWN DOWN DOWN");

header('Content-type: image/png');
imagepng($label);
imagedestroy($label);
die();
?>

这就是我得到的:

令我惊讶的是 "down" 文本消失了。这是为什么?图片前加的文字没问题,加的文字不知为何变黑了

您的代码有点乱,"DOWN.." 如果您删除第二个,则会出现文本:

$color = imagecolorallocate($label, 255, 255, 255);

您没有填充原始图像,您稍后尝试填充颜色错误($white 来自 $pic,而不是 $label)。 我清理了它:

<?php
session_start();
error_reporting(E_ALL);

$label = imagecreate(500, 500);
$black = imagecolorallocate($label, 0, 0, 0);
$white = imagecolorallocate($label, 255, 255, 255);
imagefill($label, 0, 0, $black);

imagettftext($label, 50, 0, 0, 150, $white, "arial.ttf", "UP UP UP");

$src = imagecreatefromjpeg("adidas.jpg");
$pic = imagecreatetruecolor(500, 500);
imagecopyresampled($label, $src, 0, 0, 0, 0, 150, 150, imagesx($src), imagesy($src));
$white2 = imagecolorallocate($pic, 255, 255, 255);

imagettftext($label, 50, 0, 0, 350, $white, "arial.ttf", "DOWN DOWN DOWN");

ob_end_clean();
header('Content-type: image/png');
imagepng($label);

imagedestroy($src);
imagedestroy($pic);
imagedestroy($label);
die();
?>