PHP GD Imagettftext透明

PHP GD Imagettftext透明,php,transparency,gd,imagettftext,Php,Transparency,Gd,Imagettftext,我正在尝试使用imagettftext编写透明文本,但我无法(使用imagestring可以工作,但无法选择自己的字体和大小)。最终的图像应该是一个带有透明文本的灰色矩形,这样,如果我把图像放在一个新的背景上,背景在文本中是可见的 我的代码是: $font = "./Verdana.ttf"; $fontSize = 12; $img = imagecreatetruecolor(600, 600); imagealphablending($img, false); imagesavealpha

我正在尝试使用
imagettftext
编写透明文本,但我无法(使用
imagestring
可以工作,但无法选择自己的字体和大小)。最终的图像应该是一个带有透明文本的灰色矩形,这样,如果我把图像放在一个新的背景上,背景在文本中是可见的

我的代码是:

$font = "./Verdana.ttf";
$fontSize = 12;
$img = imagecreatetruecolor(600, 600);
imagealphablending($img, false);
imagesavealpha($img, true);
$transparent = imagecolorallocatealpha($img, 255, 255, 255, 127);
$grey = imagecolorallocate($img, 127, 127, 127);
imagefilledrectangle($img, 0, 0, $imageX, $imageY, $grey);
imagettftext($img, $fontSize, 0, $text_posX, $text_posY, $transparent, $font, "This is a transparent text");
imagepng($img);
这里的解决方案应该很简单;切换到非混合模式(通过
imagealphablending($img,false);
)并添加具有完全透明颜色的文本。但是PHP中似乎存在一个bug(在7.0.7中进行了测试,最晚在编写本文时测试过),这导致文本呈现为一系列矩形而不是字母

一个非常快速简单的解决方法是取消
$transparent
的颜色索引以禁用抗锯齿:

imagettftext($img, $fontSize, 0, $text_posX, $text_posY, -$transparent, $font, 'TEST');
但是,如果您希望对文本进行抗锯齿处理,可以:

  • 以所需大小的两倍(宽×2,高×2)创建图像
  • 使用上面的否定方法添加别名文本
  • 通过
    imagecopyresampled()
    调整图像大小(宽度÷2,高度÷2),以模拟基本的抗锯齿效果
因此,基本上,这:

$font = "./Verdana.ttf";
$fontSize = 24; // note: double your original value.
$img = imagecreatetruecolor(1200, 1200); // note: double your original values.
imagealphablending($img, false);
imagesavealpha($img, true);
$transparent = imagecolorallocatealpha($img, 255, 255, 255, 127);
$grey = imagecolorallocate($img, 127, 127, 127);
imagefilledrectangle($img, 0, 0, $imageX, $imageY, $grey);
imagettftext($img, $fontSize, 0, $text_posX, $text_posY, -$transparent, $font, "This is a transparent text");

$dest = imagecreatetruecolor(600, 600);
imagealphablending($dest, false);
imagesavealpha($dest, true);
imagecopyresampled($dest, $img, 0, 0, 0, 0, 600, 600, 1200, 1200);

header('Content-Type: image/png');
imagepng($dest);

我很高兴能帮上忙。请注意,StackOverflow的礼仪是“接受”解决问题的答案。请参阅帮助中心中的“”。