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

时间:2018-09-13 20:56:38

标签: php html image gd imagecreatefrompng

我正在尝试创建一个带有一些文本和可缩放图片的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();
?>

使用上面的代码,您将获得以下图片,这是正确的:

enter image description here

现在我正尝试在其中添加小图片,因此我正在从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();
?>

这就是我得到的:

enter image description here

令我惊讶的是,“向下”文字消失了。这是为什么?在图片前添加 的文本很好,在图片后添加 的文本由于某种原因变为黑色

1 个答案:

答案 0 :(得分:0)

您的代码有点混乱,如果您第二次删除,则会显示“ 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();
?>