Php GD添加文本到png图像总是遵循图像的背景颜色


Php GD add text to png image always follow image background color

使用gd库将文本添加到png图像时,文本始终遵循图像背景颜色,即使我使用imagecolorallocate()设置了颜色,为什么会这样?

这是我的代码:

<?php
header ('Content-Type: image/png');
$im = imagecreatefrompng('picture.png');
$text_color = imagecolorallocate($im, 233, 14, 91);
$text = 'A Simple Text String';
$font_path = './font/arial.ttf';
imagettftext($im, 16, 0, 100, 200, $text_color, $font_path, $text);
imagepng($im);
imagedestroy($im);
?>

如果您正在加载一个8位的PNG文件,那么调色板中的所有256个条目都已经被分配了。对imagecolorallocate()的调用将返回false。它被转换为0,这可能是背景颜色的索引。

你应该做的是调用imagecolorstotal()来查看它是否小于256。如果调色板已满,请在继续之前将图像转换为真彩色。